//
//  TKGeXianWaiQinNewHomepageVC.m
//  泰行销
//
//  Created by pangpang on 2021/10/20.
//  Copyright © 2021 taikanglife. All rights reserved.
//

#import "TKGeXianWaiQinNewHomepageVC.h"
#import "TKGeXianWaiQinNaviBar.h"
#import "EllipsePageControl.h"
#import "TKHomePageToolsBar.h"
#import "TKCustomerTimer.h"
#import "TKTanChuangView.h"
#import "TKHuoKeModel.h"
#import "TKHPWebController.h"
#import "TKWebView.h"
#import "TKGDViewController.h"
#import "TKJumpManger.h"
#import "TKLocationManager.h"
#import "TKBirthdayPopView.h"
#import "TKSuggestViewController.h"
#import "TKGeXianWaiQinHomepageHeader.h"
#import "OpenUDID.h"
#import "TKFingerAlertView.h"
#import "TKUpdateView.h"
#import "TKExpressNewsCell.h"
#import "TKSearchMiddleVC.h"
#import "TKTabBarController.h"
#import "TKKnowledgeViewController.h"
#import "TKQRCodeUtil.h"
#import "TKKlModuleModel.h"
#import "TKBranchCompanyModel.h"
#import "TKTimeProxy.h"
#import "TKGeXianWaiQinHomeLiveTableViewCell.h"
#import "TKBranchCompanyCell.h"
#import "TKQrResultViewController.h"
#import "TKHomeKnowledgeModel.h"
#import "TKZYTipsView.h"
#import "TKGeXianWaiQinHaiBaoAndShorVideoCell.h"
#import "TKHomeNewTouTiaoTableCell.h"
#import "JPUSHService.h"
#import "ConstanceOfSingnWithBlueTooth.h"
#import "AutoAlertView.h"
#import "NSDate+Additions.h"
#import "UIImage+image.h"
#import "TKCircleScrollView/TKCircleScrollView.h"
#import "TKCompanyAndEBStoreTableViewCell.h"
#import "TKHomeIntelAssistViewModel.h"
#import "TKHuoKeZhuanQuTableViewCell.h"
#import "TKGeXianWaiQinHomeGuideView.h"
#import "TKTaiZhiHuModel.h"
#import "isalessystem-Swift.h"
#import "UIImage+YCHUD.h"
#import "UIImage+GIF.h"
#import "TKGeXianWaiQinTouTiaoLastCell.h"
#import "TKGeXianWaiQinDianBoModel.h"
#import "TKBannerModel.h"

//每个cell的高度
#define cellH kFitRatio_750(90)
//蓝牙打卡baseURL
#define KBluetoothBaseURL isTKProduction?BlueToothSignBaseURL:BlueToothSignBaseURLTest
//
#define minH(value) [TextFrame frameOfText:@"呵呵" With:[UIFont systemFontOfSize:FONT_PT(value)] Andwidth:100].height
@interface TKGeXianWaiQinNewHomepageVC ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIGestureRecognizerDelegate,WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>
@property (nonatomic,weak) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *array;
@property (nonatomic,weak) TKGeXianWaiQinNaviBar *bar;
@property (nonatomic,copy) NSString *currentPage;//当前页码
@property (nonatomic,assign) BOOL isRefreshing;//是否正在刷新
@property (nonatomic,assign) int errorHappen;//是否发生错误 0:没有发生 1:数据为空 2：其他错误
@property (nonatomic,strong) NSMutableArray *bannerArray;
@property (nonatomic,strong) TKDisconnectionWarning *warnning;
@property (nonatomic,strong) NSArray *homeIconAry;
@property (nonatomic,strong) UIView *header;
@property (nonatomic,assign) BOOL isCanUseSideBack;
@property (nonatomic,strong) NSMutableArray <TKHuoKeModel *>*huokeArray;//存放获客模型数据
@property (nonatomic,strong) NSMutableArray <TKTaiZhiHuModel *>*taizhihuArray;//存放获客模型数据
@property (nonatomic,strong) NSMutableArray *branchCompanyArray;//存放分公司专区模型数据
@property (nonatomic, strong) TKHomeIntelAssistViewModel *intelAssistViewModel;
@property (nonatomic,strong) NSMutableArray *expressNewArray;//今日爆单,快报个险外勤不要了
@property (nonatomic, strong) NSMutableArray *moduleModels;//知识库
@property(nonatomic,strong) EllipsePageControl *myPageControl;
@property (nonatomic,strong) TKHomePageToolsBar *toolBar;
@property (nonatomic,assign) BOOL hasHKLimit;///<是否有展业证（无不显示获客专区）
/*保存微海报请求返回数据*/
@property (nonatomic, strong)NSDictionary * haiBaoResonsed;
/*定时器*/
@property (nonatomic, strong)TKCustomerTimer * customerTimer;
/*假数据测试--剩余秒数*/
@property (nonatomic, assign)NSInteger  secondCount;
/*直播和短视频数据字典*/
@property (nonatomic, strong)NSMutableDictionary * liveVideoDict;
/*直播和短视频数据字典*/
@property (nonatomic, strong)NSMutableArray * dianboArr;
/*头条更多跳转链接*/
@property (nonatomic, strong)NSString * moreItemUrl;
/*aboutCompanyArray*/
@property (nonatomic, strong)NSMutableArray * aboutCompanyArray;
/*微海报短视频状态*/
@property (nonatomic, assign)BOOL  videoState;
@property (nonatomic,strong) NSString  * criticalPointPic ;
@property(nonatomic,strong) TKTanChuangView *tanchuangView;
@property(nonatomic,strong) TKCircleScrollView *circleScrollView;//首页轮播
@property (nonatomic,copy) NSArray * headerArray ;
@property (nonatomic,retain) UIView * myview ;//首页渐变
@property (nonatomic,copy) NSString * taizhihuMoreUrl ;
@property (nonatomic,assign) BOOL isLive ;
@property (nonatomic,copy) NSString * dianboMoreUrl ;


@end

@implementation TKGeXianWaiQinNewHomepageVC
-(TKCircleScrollView *)circleScrollView{
    if (!_circleScrollView) {
        _circleScrollView = [[TKCircleScrollView alloc]initWithFrame:CGRectMake(0, kFitRatio_750(20), TKScreenWidth, kFitRatio_750(120)) margin:(TKScreenWidth-kFitRatio_750(330)) / 2 lineSpace:kFitRatio_750(11) scale:0.8];
    }
    return _circleScrollView;
}
- (NSMutableArray *)dianboArr{
    if (!_dianboArr) {
        _dianboArr = @[].mutableCopy;
    }
    return _dianboArr;
}
- (NSString *)taizhihuMoreUrl{
    if (!_taizhihuMoreUrl) {
        _taizhihuMoreUrl = @"";
    }
    return _taizhihuMoreUrl;
}
-(TKDisconnectionWarning *)warnning
{
    if (_warnning == nil) {
        _warnning = [[TKDisconnectionWarning alloc]init];
        _warnning .frame = CGRectMake(0, TKHeaderH, TKScreenWidth, kFitRatio_750(33));
        
    }
    return _warnning;
}
- (NSString *)dianboMoreUrl{
    if (!_dianboMoreUrl) {
        _dianboMoreUrl = @"";
    }
    return _dianboMoreUrl;
}
- (NSString *)criticalPointPic{
    if (!_criticalPointPic) {
        _criticalPointPic = @"";
    }
    return  _criticalPointPic;
}
-(NSMutableArray *)bannerArray
{
    if (!_bannerArray) {
        _bannerArray = [NSMutableArray array];
    }
    return _bannerArray;
}
//- (NSMutableArray *)secondBannerArray{
//    if (!_secondBannerArray) {
//        _secondBannerArray = [NSMutableArray array];
//    }
//    return _secondBannerArray;
//}
-(NSMutableArray *)array
{
    if (_array == nil) {
        _array = [NSMutableArray array];
    }
    return _array;
}
- (NSMutableArray<TKHuoKeModel *> *)huokeArray{
    if(!_huokeArray){
        _huokeArray = [NSMutableArray array];
    }
    return _huokeArray;
}
-(NSMutableArray<TKTaiZhiHuModel *> *)taizhihuArray{
    if(!_taizhihuArray){
        _taizhihuArray = [NSMutableArray array];
    }
    return _taizhihuArray;
}
- (NSMutableArray *)branchCompanyArray{
    if (!_branchCompanyArray) {
        _branchCompanyArray = [NSMutableArray array];
    }
    return _branchCompanyArray;
}
- (NSMutableArray *)expressNewArray{
    if (!_expressNewArray) {
        _expressNewArray = [NSMutableArray array];
    }
    return _expressNewArray;
}
- (NSMutableArray *)moduleModels{
    if (!_moduleModels) {
        _moduleModels = [NSMutableArray array];
    }
    return _moduleModels;
}

-(NSString *)currentPage
{
    if (_currentPage == nil) {
        _currentPage = @"1";
    }
    return _currentPage;
}

-(EllipsePageControl *)myPageControl{
    
    if (_myPageControl==nil) {
        _myPageControl = [[EllipsePageControl alloc] init];
        _myPageControl.numberOfPages = 2;
        _myPageControl.currentColor = TKMainColor;
        _myPageControl.otherColor = [UIColor clearColor];
        _myPageControl.controlSize = 2;
        _myPageControl.controlSpacing = 1;
        _myPageControl.controlSizeWidth = 15;
    }
    return _myPageControl;
}
-(void)setHomeIconAry:(NSArray *)homeIconAry{
    if (_homeIconAry == homeIconAry) {
        return ;
    }
    _homeIconAry = homeIconAry;
    for (UIView *subview in self.header.subviews) {
        if ([subview isKindOfClass:[TKHomePageToolsBar class]]) {
            [subview removeFromSuperview];
        }
    }
    NSMutableArray *tempAry = [NSMutableArray array];
    [tempAry addObjectsFromArray:homeIconAry];

    //易投常年占据首位
    NSDictionary *yitoudict = @{@"logoImgUrl":@"",@"targetType":@"native",@"resourceName":@"易投",@"resourcePath":@"易投",@"type":@"",@"url":@"",@"blocked":@"",@"tip":@""};
    TKFunctionModel *yitouModel = [TKFunctionModel mj_objectWithKeyValues:yitoudict];
    [tempAry insertObject:yitouModel atIndex:0];
    if (tempAry.count >19) {
        [tempAry removeLastObject];
    }
    
    NSDictionary *dict = @{@"logoImgUrl":@"",@"targetType":@"native",@"resourceName":@"更多",@"resourcePath":@"更多",@"type":@"",@"url":@"",@"blocked":@"",@"tip":@""};
    TKFunctionModel *moreModel = [TKFunctionModel mj_objectWithKeyValues:dict];
    [tempAry addObject:moreModel];
    //设置toolBar
    TKHomePageToolsBar *toolsBar = [TKHomePageToolsBar initWithAry:tempAry];
    self.toolBar = toolsBar;
    self.toolBar.backgroundColor = [UIColor clearColor];
    [self.header addSubview:toolsBar];
    NSInteger lineN = ((tempAry.count%5)?(tempAry.count/5+1):(tempAry.count/5));
    if (lineN>2) {
        lineN = 2;
    }
    CGFloat toolBarH = lineN*(kFitRatio_750(40)+minH(20)+kFitRatio_750(5))+(lineN-1)*kFitRatio_750(5)+kFitRatio_750(10)*2+kFitRatio_750(15) - kFitRatio_750(5) +kFitRatio_750(13);
    toolsBar.frame = CGRectMake(0, self.circleScrollView.bottom+kFitRatio_750(10), TKScreenWidth, toolBarH);
    if (tempAry.count>10 && tempAry.count <= 20) {
        toolsBar.contentSize  = CGSizeMake(2 * TKScreenWidth, toolBarH);
        toolsBar.pagingEnabled = YES;
        toolsBar.showsHorizontalScrollIndicator = NO;
        toolsBar.delegate = self;
        toolsBar.scrollEnabled = YES;
    }else{
        toolsBar.contentSize = CGSizeMake(TKScreenWidth, toolBarH);
        toolsBar.scrollEnabled = NO;
    }
    [self didClickBtn:toolsBar withAry:tempAry];
    self.header.frame = CGRectMake(0, 0, TKScreenWidth, toolsBar.bottom);
    self.myPageControl.frame = CGRectMake((TKScreenWidth-kFitRatio_750(25))/2, toolsBar.bottom-kFitRatio_750(20), 30, kFitRatio_750(10));
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake((TKScreenWidth-kFitRatio_750(25))/2, toolsBar.bottom-kFitRatio_750(20) + (kFitRatio_750(10) - 2)/2 +0.5, 29, 3)];
    view.layer.cornerRadius = 1.5;
    view.backgroundColor = [UIColor colorWithHexString:@"eeeeee"];
    [self.header addSubview:view];
    [self.header addSubview:self.myPageControl];
    if (tempAry.count<=10) {
        self.myPageControl.hidden = YES;
        toolsBar.height = toolBarH - kFitRatio_750(20);
        self.header.height = toolsBar.bottom;
    }else{
        self.myPageControl.hidden = NO;
        toolsBar.height = toolBarH;
        self.header.height = toolsBar.bottom;
    }
    if (self.myPageControl.currentPage==1) {
        [toolsBar scrollRectToVisible:CGRectMake(TKScreenWidth, 0, toolsBar.width, toolsBar.height) animated:YES];
    }
    self.tableView.tableHeaderView = self.header;
}

- (void)didClickBtn:(TKHomePageToolsBar *)toolsBar withAry:(NSArray *)ary{
    
    WeakSelf;
    toolsBar.TKToolBarBlock = ^(NSInteger index){
        
        TKFunctionModel *model = ary[index];
        
        if(![model.resourcePath isEqualToString:@"更多"]){
            /// 保存为最近使用
            [TKLocalManager setRecentlyused:model.resourcePath];
        }

        [weakSelf didClickBtn:model.resourcePath];
    };
}
#pragma mark - 按钮点击事件
- (void)didClickBtn:(NSString *)path{
    TKFunctionModel *model = [TKLocalManager getModelWithPath:path];
    if ([path isEqualToString:@"更多"]) {
        model = [[TKFunctionModel alloc] init];
        model.resourcePath = @"/$$$$";
        model.resourceName = @"更多";
    }
    if ([path isEqualToString:@"易投"]) {
        model = [[TKFunctionModel alloc] init];
        model.resourcePath = @"/$$$0";
        model.resourceName = @"易投";
    }
    if ([model.resourceName isEqualToString:@"易投"]) {
        [[SensorsAnalyticsSDK sharedInstance] track:home_otherEntrance_click withProperties:@{@"buttonName":@"易投",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
    }else{
    [[SensorsAnalyticsSDK sharedInstance] track:home_homePage_functionArea withProperties:@{@"functionId":model.resourcePath?:@"",@"buttonName":model.resourceName?:@"",@"pageName":@"首页",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
    }
    if ([path isEqualToString:@"/1015"]) {
        if ([AppDelegate getAppDelegate].YLUrl) {
            if (!IsEmptyValue([AppDelegate getAppDelegate].YLUrl)) {
                TKHPWebController *web = [[TKHPWebController alloc]init];
                web.url = [AppDelegate getAppDelegate].YLUrl;
                web.name = @"养老社区";
                web.logoUrl = nil;
                web.intro = @"";
                [self.navigationController pushViewController:web animated:YES];
            }
        }else
        {
            [self getUrlWith:NO];
        }
        return;
    }
    if ([path isEqualToString:@"/1029"]) {
        
        [self getRunDataTypeWithLoading:YES];
        return;
    }
    // 新兵营
    if ([path isEqualToString:@"/1080"]) {
        [self getxinbingyin];
        return;
    }
    if ([path isEqualToString:@"更多"]) {
        WeakSelf;
        TKGDViewController *gd = [[TKGDViewController alloc]init];
        gd.block = ^(NSArray *homeIconAry) {
            weakSelf.homeIconAry = homeIconAry;
        };
        gd.homeIconNameAry = [NSMutableArray arrayWithArray:self.homeIconAry];
        [self.navigationController pushViewController:gd animated:YES];
        return;
    }
    if ([path isEqualToString:@"易投"]) {
            TKSuiXinTouVC *ytvc = [[TKSuiXinTouVC alloc] initWithNeedBack:YES customId:nil customType:nil];
         [self.navigationController pushViewController:ytvc animated:YES];
        return;
    }
    [TKJumpManger jumpFrom:self toControllerWithPath:path];
}

#pragma mark - 跳转到机器人聊天
/// 跳转到机器人聊天
- (void)jumpToIM{
    //跳转IM入口空白页面
    TKWebViewController *vc = [[TKWebViewController alloc]init];
    vc.url = isTKProduction?@"https://titan.mobile.taikang.com/imh5/#/message?fromSource=TXXH5":@"http://titantest.mobile.taikang.com/imh5/#/message?fromSource=TXXH5";
    [self.navigationController pushViewController:vc animated:YES];
    [[SensorsAnalyticsSDK sharedInstance] track:home_otherEntrance_click withProperties:@{@"buttonName":@"IM聊天",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setPushTas];
    self.secondCount = 0;
    [self getJsPushTags];
    self.errorHappen = 0;
    self.isLive = YES;
    self.headerArray = @[@"",@"智能助理",@"",@"获客专区",@"泰知乎",@"圈子经营",@"精彩直播",@"泰康头条",@"关于泰康"];

    self.intelAssistViewModel = [[TKHomeIntelAssistViewModel alloc]init];
    WeakSelf
    self.intelAssistViewModel.segmentDidClick = ^(NSUInteger index) {
        [UIView performWithoutAnimation:^{
            [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
        }];
    };
    self.intelAssistViewModel.addScheduleBtnDidClick = ^(NSString * _Nonnull addRcUrl) {
        /// 添加日程
        TKLog(@"添加日程点击: %@", addRcUrl);
        if (addRcUrl.length == 0) {
            return;
        }
        TKWebViewController *webVC = [[TKWebViewController alloc]init];
        webVC.url = addRcUrl;
        [weakSelf.navigationController pushViewController:webVC animated:YES];
    };

    //    self.secondBannerHeight = 0.0;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    self.currentPage = @"0";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.delegate = self;
    [self setTableView];
    [self setTableVIewHeader];
    [self setNav];
    [self getBranchCompanyData];

    ///调用今日爆点请求
        [self getDailyCriticalPointData];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeAccount) name:TKChangeAccount object:nil];
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self getUserBirthday];
    [self aboutTheCompany];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self showTrainDialog];
    });
    ///定位
        [self location];
        /// 开启轨迹收集
            [TKLocationManager sharedManager].didChangeLocationAuthStatus = ^(CLAuthorizationStatus status) {
                if (status == 2) {
                    [TKCodeErrorView showAlertInfo:@"定位权限未开启，无法正常使用泰行销，请前往”设置->隐私->定位服务“中允许泰行销使用定位服务" sureClick:^{
    //                    exit(0);
                    }];
                }
            };
            [[TKLocationManager sharedManager]startUploadTimer];
//        }
    //弹框整合
    [self dialogGetAll];

    /// 引导图
    [self showGuide];
    /// 监听应用从后台进入前台
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterForegroundAction) name:@"TKEnterForeground" object:nil];
}
- (void)showGuide{
    if (![TKUserDefaults valueForKey:@"GeXianWaiQinHomeDidShow"]) {
        TKGeXianWaiQinHomeGuideView *guideView = [[TKGeXianWaiQinHomeGuideView alloc]initWithFrame:TKKeywindow.bounds];
        [guideView show];
        [TKUserDefaults setValue:@"1" forKey:@"GeXianWaiQinHomeDidShow"];
    }
}
- (void)enterForegroundAction{
    [self getIntelAssistData];
}
#pragma mark - 弹窗整合
-(void) dialogGetAll{
    NSString *url = @"https://isaleuat.taikang.com/isales-platform-home/dialog/getAll";
    if (isTKProduction) {
        url = @"https://isales.taikang.com/isales-platform-home/dialog/getAll";
    }
    WeakSelf
    [TKHttpTools getWithUrl:url paramDict:@{} andNeedAlert:NO success:^(id responseObject) {
        TKLog(@"dialog/getAll : %@",responseObject);
        /**{
            "dialogType": "link", 弹框的类型img图片，link链接
            "identity": "y",身份：n内勤，y外勤
            "channel": "2",渠道
            "dialogGotoUrl": "111111111", 弹框跳转链接
            "dialogTitle": "456",弹框标题
            "id": "3e269e5f2e094f498db0d29eee826acf",弹框编号
            "dialogUrl": "13465",弹框链接
            "dialogImgUrl": ""弹框图片
        }*/
        NSArray *infoArr = responseObject[@"info"];
        TKTanChuangView *tanchuangView = [[TKTanChuangView alloc] initWithFrame:CGRectMake(0, 0, TKScreenWidth, TKScreenHeight)];
        weakSelf.tanchuangView = tanchuangView;
        tanchuangView.dataAry = infoArr;
        tanchuangView.closeTanchuangView = ^{
            for (UIView *subView in weakSelf.tanchuangView.subviews) {
                [subView removeFromSuperview];
            }
            [weakSelf.tanchuangView removeFromSuperview];
        };
        tanchuangView.clickTanchuangView = ^(NSInteger index) {
            NSDictionary *dataDic = infoArr[index];
            if (!IsEmptyValue(dataDic[@"dialogGotoUrl"])) {
                TKWebViewController *vc = [[TKWebViewController alloc]init];
                vc.url = dataDic[@"dialogGotoUrl"];
                [weakSelf.navigationController pushViewController:vc animated:YES];
                [TKKeywindow sendSubviewToBack:weakSelf.tanchuangView];
            }
        };
        for (UIView *subView in TKKeywindow.subviews) {
            if ([subView isKindOfClass:[TKTanChuangView class]]) {
                [subView removeFromSuperview];
            }
        }
        if (infoArr.count) {
            [TKKeywindow addSubview:weakSelf.tanchuangView];
        }
        
        [self showMIMAGuoQi];

        
    } failure:^(NSError *error) {
        
        [self showMIMAGuoQi];


    }];
}
-(void)showMIMAGuoQi{
    NSString *pwdWarnning = [TKUserDefaults objectForKey:@"TKpwdWarnning"];
    if (pwdWarnning) {
        [AutoAlertView ShowMessage:pwdWarnning];
        [TKUserDefaults removeObjectForKey:@"TKpwdWarnning"];
    }
}
#pragma mark -生日弹窗
- (void)getUserBirthday{
    NSString *url = @"https://sspuat.taikang.com/attendance/teamBirth/getUserBirthFlag";
    if (isTKProduction) {
        url = @"https://ssp.taikang.com/basic/attendance/teamBirth/getUserBirthFlag";
    }
    [TKHttpTools getWithUrl:url paramDict:@{} andNeedAlert:NO success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        if ([responseObject[@"info"][@"birthWindowFlag"] boolValue]) {
            [TKBirthdayPopView show];
        }
    } failure:^(NSError *error) {
        
    }];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    if (@available(iOS 13.0, *)) {
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
    } else {
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    }
    [[SensorsAnalyticsSDK sharedInstance] track:home_homePage withProperties:@{@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
    for (UIView *subview in TKKeywindow.subviews) {
        if (subview.isHidden == YES && ([subview isMemberOfClass:[WKWebView class]]||[subview isMemberOfClass:[TKFingerAlertView class]]||[subview isMemberOfClass:[TKUpdateView class]]||[subview isMemberOfClass:[TKWebView class]]||[subview isMemberOfClass:[TKTanChuangView class]])) {
            subview.hidden = NO;
            [TKKeywindow bringSubviewToFront:subview];
        }
    }
    

    
    [self cancelSideBack];
    [self addanserwerButton];
    /// 上传本地缓存的定位
    [[TKLocationManager sharedManager]uploadCacheLocation];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self startSideBack];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    for (UIView *subview in TKKeywindow.subviews) {
        if (subview.isHidden == NO && ([subview isMemberOfClass:[WKWebView class]]||[subview isMemberOfClass:[TKFingerAlertView class]]||[subview isMemberOfClass:[TKUpdateView class]]||[subview isMemberOfClass:[TKWebView class]]||[subview isMemberOfClass:[TKTanChuangView class]])) {
            subview.hidden = YES;
        }
    }
}
- (void)showTrainDialog{
    NSString *url = [TKKQUrl stringByAppendingString:@"dialog/list"];
    [TKHttpTools getWithUrl:url paramDict:@{@"imei":[OpenUDID value]} andNeedAlert:NO success:^(id responseObject) {
        TKLog(@"%@",responseObject);
        NSArray *arr = responseObject[@"info"];
        if (arr.count == 0) {
            return;
        }
        for (NSDictionary *dic in arr) {
            NSString *type = dic[@"type"];
            if (![type isEqualToString:@"h5"]) {
                continue;
            }
            NSString *url = dic[@"url"];
            if (!url) {
                continue;
            }
            TKHomeAlertModel *model = [TKHomeAlertModel mj_objectWithKeyValues:dic];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [self initWebViewWithData:model];
            });
        }
    } failure:^(NSError *error) {
        
    }];
}
- (NSArray *)getAllHandlerNames{
    return @[@"getUserInfoByNative",@"getSign",@"checkSign",@"getAppInfo",@"encrypt",@"decrypt"];
}

- (void)initWebViewWithData:(TKHomeAlertModel *)model{
    
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    WKUserContentController *user = [[WKUserContentController alloc]init];
    [user addScriptMessageHandler:self name:@"openPageByNative"];
    [user addScriptMessageHandler:self name:@"closeByNative"];
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
    config.selectionGranularity = WKSelectionGranularityDynamic;
    WKPreferences *fre = [WKPreferences new];
    fre.javaScriptCanOpenWindowsAutomatically = YES;
    config.preferences = fre;
    config.userContentController =user;
    config.preferences = preferences;
    config.allowsInlineMediaPlayback = YES;
    config.mediaPlaybackRequiresUserAction = false;
    
    TKWebView *webV = [[TKWebView alloc]initWithFrame:TKKeywindow.bounds configuration:config];
    webV.eventHandler = [[TKWebEventHandler alloc]init];
    NSArray *defaultHandlerNames = [self getAllHandlerNames];
    [defaultHandlerNames enumerateObjectsUsingBlock:^(NSString*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [user addScriptMessageHandler:webV.eventHandler name:obj];
    }];

    
    
    [webV evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        if (error) { return; }
        NSString *userAgent = result;
        if (![userAgent containsString:@"/isales/TXX-iOS"]) {
            userAgent = [userAgent stringByAppendingString:@"/isales/TXX-iOS"];
            NSDictionary *dict = @{@"UserAgent": userAgent};
            [TKUserDefaults registerDefaults:dict];
        }
    }];
    
    webV.navigationDelegate = self;
    webV.model = model;
    if (@available(iOS 11.0, *)) {
        webV.scrollView.contentInset = UIEdgeInsetsMake(-TKStautsBarH, 0, 0, 0);
        webV.height +=TKStautsBarH;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    NSString *urlStr = model.dialogUrl;
    
    if ([urlStr containsString:@" "]) {
        urlStr = [urlStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    NSURL *url = [urlStr mj_url];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.f];
    webV.scrollView.bounces = NO;
    [webV setOpaque:NO];
    [webV loadRequest:request];
    [self addwebView:webV];
    [self sendViewToBack:webV];
}
-(void) addwebView:(TKWebView *)webView{
//    [self.tabBarController.view addSubview:webView];
        [TKKeywindow addSubview:webView];
}
- (void)sendViewToBack:(TKWebView *)webv{
    [TKKeywindow sendSubviewToBack:webv];
}
#define mark  --WKWebView delegate
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    if (webView.superview) {
        [TKKeywindow bringSubviewToFront:webView];
    }
}

-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    if (webView.superview) {
        [webView removeFromSuperview];
    }
}

-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    if (webView.superview) {
        [webView removeFromSuperview];
    }
}
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    TKLog(@"%@------%@",message.name,message.body);
    TKWebView *webV = (TKWebView *)message.webView;
    TKHomeAlertModel *model = webV.model;
    if ([message.name isEqualToString:@"openPageByNative"]) {
        if (model.gotoType.length > 0) {/// 后台返回了跳转信息
            [self openPageFromServer:model];
        }else{/// h5返回跳转信息
            /**
             {
             "type":"h5/path",
             "path":"/1010",
             "gotoUrl":"https://dfgyuijhgfjkl"
             }
             */
            NSDictionary *param;
            if ([message.body isKindOfClass:[NSString class]]) {
                param = [NSDictionary dictionaryWithJsonString:message.body];
            }else{
                param = message.body;
            }
            [self openPageFromH5:param serverModel:model];
        }
        /// 判断是否要弹窗消失
        if([model.dismiss isEqualToString:@"0"]){/// 不消失
            return;
        }
        if (webV.superview) {
            [self sendViewToBack:webV];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [webV removeFromSuperview];
            });
        }
    }
    if ([message.name isEqualToString:@"closeByNative"]) {
        NSDictionary *param;
        if ([message.body isKindOfClass:[NSString class]]) {
            param = [NSDictionary dictionaryWithJsonString:message.body];
        }else{
            param = message.body;
        }
        if (webV.superview) {
            [self sendViewToBack:webV];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [webV removeFromSuperview];
            });
        }
    }
}
- (void)openPageFromServer:(TKHomeAlertModel *)model{
    if ([model.gotoType isEqualToString:@"path"]) { //原生功能
        NSString *path = model.gotoUrl;
        NSArray *items = [TKLocalManager sharedManager].allSubFunctionAry;//用户权限数组
        NSMutableArray *tempAry = [NSMutableArray array];//存储用户所有权限的路径
        [items enumerateObjectsUsingBlock:^(TKFunctionModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [tempAry addObject:obj.resourcePath];
        }];
        if ([path length]) {
            if ([tempAry containsObject:path]) { //跳更多里的功能
                [self didClickBtn:path];
            }else{
                if ([path isEqualToString:@"feedbackPage"]) {
                    TKSuggestViewController *vc = [[TKSuggestViewController alloc]init];
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
        }
    }else{
        TKWebViewController *vc = [[TKWebViewController alloc]init];
        vc.url = model.gotoUrl;
        if ([model.share isEqualToString:@"y"]) {
            TKShareModel *shareModel = [[TKShareModel alloc]initWithShareUrl:model.shareUrl shareTitle:model.shareTitle shareBitmap:model.shareLogo shareIntroduce:model.shareDesc secret:@""];
            vc.shareModel = shareModel;
        }
        [self.navigationController pushViewController:vc animated:YES];
    }
}
- (void)openPageFromH5:(NSDictionary *)param serverModel:(TKHomeAlertModel *)model{
    NSString *gotoUrl = param[@"gotoUrl"];
    NSString *path = param[@"path"];
    if (gotoUrl.length > 0) {/// 跳转h5页面
        TKWebViewController *vc = [[TKWebViewController alloc]initWithUrl:param[@"gotoUrl"]];
        if ([model.share isEqualToString:@"y"]) {
            TKShareModel *shareModel = [[TKShareModel alloc]initWithShareUrl:model.shareUrl shareTitle:model.shareTitle shareBitmap:model.shareLogo shareIntroduce:model.shareDesc secret:@""];
            vc.shareModel = shareModel;
        }
        [self.navigationController pushViewController:vc animated:YES];
    }else if(path.length > 0){/// 跳转原生页面
        NSArray *items = [TKLocalManager sharedManager].allSubFunctionAry;//用户权限数组
        NSMutableArray *tempAry = [NSMutableArray array];//存储用户所有权限的路径
        [items enumerateObjectsUsingBlock:^(TKFunctionModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [tempAry addObject:obj.resourcePath];
        }];
        if ([tempAry containsObject:path]) { //跳更多里的功能
            [self didClickBtn:path];
        }else{
            if ([path isEqualToString:@"feedbackPage"]) {
                TKSuggestViewController *vc = [[TKSuggestViewController alloc]init];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
    }
}
- (void)changeAccount{
    [self loadNew];
}
// MARK: === 社区问答按钮
- (void)addanserwerButton{
        [self.bar.answerButton setImage:[UIImage imageNamed:@"问答"] forState:UIControlStateNormal];
    WeakSelf
    self.bar.clickAnswerBarButton = ^{
        TKWebViewController * webVc = [[TKWebViewController alloc]init];
        NSString * urlStr = @"";
        if (isTKProduction) {
            urlStr = @"https://tzhqa.taikanglife.com/?hasTitle=f";
        }else{
            //https://tzhqatest.taikanglife.com/?hasTitle=f
            urlStr = @"https://tzhqatest.taikanglife.com/?hasTitle=f";
        }
        webVc.url = urlStr;
        [weakSelf.navigationController pushViewController:webVc animated:YES];
    };
}
#pragma mark - 定位
///定位
- (void)location{
    TKLocationManager *lm = [TKLocationManager sharedManager];
    lm = nil;
    [[TKLocationManager sharedManager]configureMapManager];
    [[TKLocationManager sharedManager]startUpdateLocation];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    if (@available(iOS 13.0, *)) {
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
    } else {
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    }
    self.navigationController.navigationBarHidden = YES;
//    self.navigationController.navigationBar.barTintColor = TKMainColor;
    
    if ([AppDelegate getAppDelegate].status == NotReachable) {
        if (!_warnning) {
            [self.view addSubview:self.warnning];
        }
    }
    
    if (_showTipsBlock) {
        _showTipsBlock();
        _showTipsBlock = nil;
    }
    [self viewImageReloadView];
}
-(void)viewImageReloadView{
    [self.tableView reloadData];
}
#pragma mark 布局
-(void)setNav
{
    
    TKGeXianWaiQinNaviBar *bar = [[TKGeXianWaiQinNaviBar alloc]init];
    __weak typeof (self)weakSelf = self;
    self.bar = bar;
    self.bar.clickLeftBarButton = ^{
        [[SensorsAnalyticsSDK sharedInstance] track:home_otherEntrance_click withProperties:@{@"buttonName":@"扫一扫",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
        [[TKQRCodeUtil shareInstance]scanQRCodeInController:self.tabBarController complete:^(NSString *result) {
            NSMutableDictionary *resDic = [NSMutableDictionary dictionary];
            if(result.length > 0){
                resDic[@"code"] = @"0";
                resDic[@"msg"] = result;
                resDic[@"desc"] = @"扫描成功";
                
                if ([result containsString:@"isales://com.taikanglife.isalessystem/jump"]) {
                    NSDictionary *params = [TKJumpManger getParamsWithUrlString:result].lastObject;
                    NSString *vcStr = params[@"module"];
                    [self didClickBtn:[NSString stringWithFormat:@"/%@",vcStr]];
                }else if ([result containsString:@"http://"]||[result containsString:@"https://"]){
                    TKWebViewController *webVc = [[TKWebViewController alloc] init];
                    webVc.url = result;
                    NSLog(@"");
                    [self.navigationController pushViewController:webVc animated:YES];
                    
                }else{
                    //展示文本描述
                    TKQrResultViewController *qrResultVc = [[TKQrResultViewController alloc] init];
                    qrResultVc.result = result;
                    [self.navigationController pushViewController:qrResultVc animated:YES];
                }
            }else{
                resDic[@"code"] = @"-100";
                resDic[@"msg"] = @"";
                resDic[@"desc"] = @"扫描失败";
            }
        }];
    };
    self.bar.searchBlock = ^{
        TKSearchMiddleVC *searchVc = [[TKSearchMiddleVC alloc]init];
        searchVc.type = @"首页";
        searchVc.prospectusType = @"";
        [weakSelf.navigationController pushViewController:searchVc animated:YES];
    };
    self.bar.clickRobotBarButton = ^{
        [[SensorsAnalyticsSDK sharedInstance] track:home_otherEntrance_click withProperties:@{@"buttonName":@"智能客服机器人",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
       //机器人跳转H5
        TKWebViewController * webVc = [[TKWebViewController alloc]init];
        NSString * urlStr = @"https://sspuat.taikang.com/preservation/html/smartrobot/index.html#/?entry=3";
        if (isTKProduction) {
            urlStr = @"https://ssp.taikang.com/preservation/html/smartrobot/index.html#/?entry=3";
        }
        webVc.url = urlStr;
        [self.navigationController pushViewController:webVc animated:YES];
    };
    self.bar.clickRightBarButton = ^{
        [weakSelf jumpToIM];
    };
    [self.bar.rightButton setImage:[UIImage imageNamed:@"消息"] forState:UIControlStateNormal];
    bar.frame = CGRectMake(0, TKStautsBarH, TKScreenWidth, TKNavgationBarH);
    [self.view addSubview:bar];
//    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
}
-(void)setTableView
{
    UITableView *table = [[UITableView alloc]initWithFrame:CGRectMake(0, TKHeaderH, TKScreenWidth, TKScreenHeight-TKHeaderH-TKSafeBottom) style:UITableViewStyleGrouped];
    table.separatorStyle = UITableViewCellSeparatorStyleNone;
    table.showsVerticalScrollIndicator = NO;
    table.showsHorizontalScrollIndicator = NO;
    self.tableView = table;
//    if (@available(iOS 11.0, *)) {
//        table.contentInset = UIEdgeInsetsMake(-TKStautsBarH, 0, 0, 0);
//    } else {
//        //         Fallback on earlier versions
//        self.automaticallyAdjustsScrollViewInsets = NO;
//    }
//    self.tableView.separatorColor = [UIColor colorWithHexString:@"#eeeeee"];
//    self.tableView.separatorColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"#f6f6f6"];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, TKScreenWidth, TKScreenHeight)];
    view.backgroundColor = [UIColor clearColor];
    view.userInteractionEnabled = YES;
    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.frame = CGRectMake(0, 0, TKScreenWidth, 621); 
    layer.colors = [NSArray arrayWithObjects:[UIColor colorWithHexString:@"#ffffff"].CGColor,[UIColor colorWithHexString:@"#f6f6f6"].CGColor, nil];
    layer.startPoint = CGPointMake(0, 0);
    layer.endPoint = CGPointMake(0, 1.0);
    [view.layer addSublayer:layer];
    self.myview = view;
    [self.tableView addSubview:view];
     [self.tableView sendSubviewToBack:view ];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TKCompanyAndEBStoreTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"GeXianWaiQinCompanyAndEBStoreCell"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TKHuoKeZhuanQuTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"huokezhuanqu"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TKHuoKeZhuanQuTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"taizhihu"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TKGeXianWaiQinTouTiaoLastCell class]) bundle:nil] forCellReuseIdentifier:@"toutiaolast"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TKHuoKeZhuanQuTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"dianbo"];
//    TKHaiBaoAndShorVideoCell
//    [self.tableView registerClass:[TKHaiBaoAndShorVideoCell class] forCellReuseIdentifier:@"quanzijingying"];
//    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TKHuoKeZhuanQuTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"quanzijingying"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TKHuoKeZhuanQuTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"zhibodianbo"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TKHuoKeZhuanQuTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"quanzijingyingTOP"];
    table.dataSource = self;
    table.delegate = self;
    __weak typeof (self)weakSelf = self;
    table.mj_header = [TKRefresh loadNewRefreshWithRefreshBlock:^{
        [weakSelf loadNew];
    }];
    [table.mj_header beginRefreshing];
    [self.view addSubview:table];
    
}
- (void)aboutTheCompany
{
    NSString * urlStr = [TKBaseUrl stringByAppendingString:@"homePage/getTkIntroductionList"];
    [TKHttpTools getWithUrl:urlStr paramDict:nil andNeedAlert:NO success:^(id responseObject) {
        TKLog(@"");
        //设置footView
        self.aboutCompanyArray = [NSMutableArray arrayWithArray:responseObject[@"info"]];
        [self footerView:self.aboutCompanyArray];
    } failure:^(NSError *error) {
        TKLog(@"%@",error);
    }];
}
- (void)footerView:(NSMutableArray *)array{
    
    //确定高度
    NSInteger columCount = (array.count -1)/3 + 1;
    CGFloat bottomViewHeight = kFitRatio_750(58) * columCount + (columCount -1) * 4 + 15 + 48 + 5;
    
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(10, 0, TKScreenWidth-20, bottomViewHeight)];
    backView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableFooterView = backView;
//    UILabel *titleLabel = [[UILabel alloc]init];
//    titleLabel.text = @"关于泰康";
//    titleLabel.font = [UIFont boldSystemFontOfSize:kFitRatio(16)];
//    [titleLabel sizeToFit];
//    titleLabel.y = 15;
//    titleLabel.x  = 10;
//    titleLabel.textColor = Color(@"#333333");
//    [backView addSubview:titleLabel];
    CGFloat imgMargin = kFitRatio_750(4);

    CGFloat imgWidth =(TKScreenWidth - 20 -20- imgMargin * 2)/3;
    CGFloat imgHeight = imgWidth/109*65;
    CGFloat margin = 10;
    UIImageView * temImgView = [[UIImageView alloc]init];
    for (int i = 0 ; i< array.count; i++) {
        NSDictionary * dict = array[i];
        
        CGFloat imgX = margin + (imgWidth + imgMargin) * (i%3);
        CGFloat imgY = (i / 3) * (4 + imgHeight)  + 10;
        UIImageView * imgView = [[UIImageView alloc]initWithFrame:CGRectMake(imgX, imgY, imgWidth, imgHeight)];
        NSString * imgUrlStr = dict[@"introductionImage"];
        NSString *imgPathStr = [imgUrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSURL * url = [NSURL URLWithString:imgPathStr];
        [imgView sd_setImageWithURL:url placeholderImage:nil];
        [backView addSubview:imgView];
        temImgView = imgView;
        UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bottomImageClick:)];
        [imgView addGestureRecognizer:tapGesture];
        imgView.userInteractionEnabled = YES;
        imgView.tag = i;
    }
    
    //添加底部view
    UIView * bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, temImgView.maxY + 15+10, TKScreenWidth, 200)];
    bottomView.backgroundColor = [UIColor colorWithHexString:@"#F4F4F4"];
    UIImageView * botImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 11, 90, 39)];
    botImageView.image = [UIImage imageNamed:@"homePage_logo"];
    botImageView.centerX = bottomView.width * 0.5;
    botImageView.contentMode = UIViewContentModeScaleAspectFit;
    [bottomView addSubview:botImageView];
    [backView addSubview:bottomView];
    CGFloat contentheight = temImgView.maxY + 15;
    UIBezierPath *path1 = [[UIBezierPath alloc]init];
    [path1 moveToPoint:CGPointMake(0, 0)];
    [path1 addLineToPoint:CGPointMake(TKScreenWidth - 20 , 0)];
    [path1 addLineToPoint:CGPointMake(TKScreenWidth - 20,contentheight - 8)];
    [path1 addArcWithCenter:CGPointMake(TKScreenWidth - 20-8, contentheight - 8) radius:8 startAngle:-M_PI endAngle:-M_PI / 2*3 clockwise:YES];
    [path1 addLineToPoint:CGPointMake(8, contentheight )];
    [path1 addArcWithCenter:CGPointMake(8,contentheight-8) radius:8 startAngle:M_PI / 2 endAngle:M_PI clockwise:YES];
    CAShapeLayer *shapeLayer1 = [CAShapeLayer layer];
    shapeLayer1.fillColor = [UIColor blueColor].CGColor;
    shapeLayer1.lineWidth = 0;
    shapeLayer1.lineJoin = kCALineJoinRound;
    shapeLayer1.lineCap = kCALineCapRound;
    shapeLayer1.path = path1.CGPath;
    backView.layer.mask = shapeLayer1;
    
}

- (void)bottomImageClick:(UIGestureRecognizer *)gesture
{
    UIImageView * imgV = (UIImageView *)gesture.view;
    NSInteger i = imgV.tag;
    NSDictionary * dict = self.aboutCompanyArray[i];
    TKWebViewController *web = [[TKWebViewController alloc] init];
    NSString * urlStr = dict[@"introductionUrl"];
    [[SensorsAnalyticsSDK sharedInstance] track:home_aboutTK_click withProperties:@{@"buttonName":dict[@"introductionName"]?dict[@"introductionName"]:@"",@"businessLine": @"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
    web.url = urlStr;
    [self.navigationController pushViewController:web animated:YES];
}
#pragma mark - 轮播图以及功能模块
-(void)setTableVIewHeader
{
    UIView *header = [[UIView alloc]init];
    self.header = header;
        header.backgroundColor = [UIColor clearColor];
    //设置banner
    __weak typeof (self)weakSelf = self;
    self.circleScrollView.backgroundColor =[UIColor clearColor];
    self.circleScrollView.itemDidClick = ^(NSUInteger index) {
        NSLog(@"circleScrollView2——点击了第%ld个",index);
        TKBannerModel *model = [weakSelf.bannerArray objectAtIndex:index];
        [weakSelf bannerToWebview:model];

        [[SensorsAnalyticsSDK sharedInstance] track:home_banner_click withProperties:@{@"contentId":model.ID?model.ID:@"",@"num":[NSString stringWithFormat:@"%lu",(unsigned long)index+1],@"title":model.title?model.title:@"",@"position":@"顶部",@"businessLine": @"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
            };
    [header addSubview:self.circleScrollView];
    [self setMyHomeFunctionAry];
}
- (void)setMyHomeFunctionAry{
    NSMutableArray *mHomeIconAry = [TKLocalManager sharedManager].homeFunctionAry.mutableCopy;
    if (mHomeIconAry.count >18) {
        [mHomeIconAry removeLastObject];
    }
    self.homeIconAry = mHomeIconAry;
}
/**
 banner跳转webview逻辑
 */
- (void)bannerToWebview:(TKBannerModel *)model{
    NSString *str = model.contentUrl;
    str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (str&&(![str isEqualToString:@""])) {
        
        if ([str isEqualToString:@"jumpToSuggestion"]) {
            
            TKSuggestViewController *vc = [[TKSuggestViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
            
        }else{
            
            if ([model.targetType isEqualToString:@"8"]) {
                if ([str containsString:@"tkphysical"]&&[TKLocalManager containsItem:@"/1038"]) {
                    NSString *pinjie = @"?";
                    if ([str containsString:@"?"]) {
                        pinjie = @"&";
                    }
                    str = [NSString stringWithFormat:@"%@%@managerNo=%@&managerCompany=%@&channelId=3&managerChannel=%@&hasTitle=y",str,pinjie,[TKLocalManager sharedManager].staffNumber,[TKLocalManager sharedManager].companyCode,[TKLocalManager sharedManager].channel];
                }
                TKWebViewController *vc = [[TKWebViewController alloc]init];
                vc.url = str;
                if(model.isShare){
                    vc.shareModel = model.shareModel;
                }
                [self.navigationController pushViewController:vc animated:YES];
            }else if([model.targetType isEqualToString:@"1"]){
                TKLocalManager *manager = [TKLocalManager sharedManager];
                NSString *paramJson = manager.planbookParam;
                NSString *url = [NSString stringWithFormat:@"%@&param=%@",str,paramJson];
                TKWebViewController *vc = [[TKWebViewController alloc]init];
                vc.url = url;
                [self.navigationController pushViewController:vc
                                                     animated:YES];
                
            }else if([model.targetType isEqualToString:@"4"]){
                [self didClickBtn:model.path];
            }else{
                TKWebViewController *vc = [[TKWebViewController alloc]init];
                vc.url = str;
                if(model.isShare){
                    vc.shareModel = model.shareModel;
                }
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
    }else{
        if([model.targetType isEqualToString:@"4"]){
            [self didClickBtn:model.path];
        }
    }
}

- (void)jumpToStudy{
    TKTabBarController *tabbarVC = (TKTabBarController *)self.tabBarController;
    [tabbarVC setSelectedIndex:3];
    [tabbarVC.tab clickIndex:3];
    return;
}
-(void)getProductSubTypeWithLoading:(BOOL) needLoading
{
    TKTabBarController *tabbarVC = (TKTabBarController *)self.tabBarController;
    [tabbarVC setSelectedIndex:1];
    [tabbarVC.tab clickIndex:1];
    return;
}

//获取知识库列表
-(void)getRunDataTypeWithLoading:(BOOL) needLoading
{
    if (self.moduleModels.count > 0) {
        TKKnowledgeViewController *baseC = [[TKKnowledgeViewController alloc] init];
        baseC.moduleModels = self.moduleModels;
        [self.navigationController pushViewController:baseC animated:YES];
    }else
    {
        if (needLoading) {
            [TKLoadingHUD showWithTitle:nil];
        }
        
        
        [TKHttpTools POSTWithURL:[TKDBBQUrl stringByAppendingString:@"oml/getModuleListNew"] parameters:@{} withWay:YES success:^(id responseObject) {
            [TKLoadingHUD dismiss];
            if ([responseObject[@"rspCode"] isEqualToString:@"0"]) {
                NSDictionary *dict1 = responseObject[@"info"];
                self.moduleModels = [TKKlModuleModel mj_objectArrayWithKeyValuesArray:dict1];
                
                TKKnowledgeViewController *baseC = [[TKKnowledgeViewController alloc] init];
                baseC.moduleModels = self.moduleModels;
                [self.navigationController pushViewController:baseC animated:YES];
            }
        } failure:^(NSError *error) {
            [TKLoadingHUD dismiss];
        }];
    }
    
}


//网络情况监听
- (void) reachabilityChanged:(NSNotification *)note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    NetworkStatus netStatus = [curReach currentReachabilityStatus];
    if (netStatus == NotReachable) {
        if (!_warnning) {
            [self.view addSubview:self.warnning];
        }
        
    }else
    {
        if (!self.array.count) {
            [self.tableView.mj_header beginRefreshing];
        }
        
        [self.warnning removeFromSuperview];
        _warnning = nil;
    }
}

-(void)getUrlWith:(BOOL)isIntro
{
    [TKHttpTools POSTWithURL:[TKBaseUrl stringByAppendingString:@"sys/showImage/"] parameters:@{@"md5":[TKUserDefaults objectForKey:@"ADMD5"]?[TKUserDefaults objectForKey:@"ADMD5"]:@"",@"channel":[[TKUserDefaults objectForKey:TKLoginUser] componentsSeparatedByString:@"_"].firstObject} withPost:NO andNeedAlert:NO success:^(id responseObject) {
        NSDictionary *dict = responseObject[@"info"];
        if (isIntro) {
            NSString *str = dict[@"company"];
            str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
            if (str&&(![str isEqualToString:@""])) {
                [[SensorsAnalyticsSDK sharedInstance] track:home_otherEntrance_click withProperties:@{@"buttonName":@"其他",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
                TKWebViewController *web = [[TKWebViewController alloc] init];
                web.url = str;
                [self.navigationController pushViewController:web animated:YES];
            }
            
        }else
        {
            NSString *str = dict[@"company"];
            str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
            if (str&&(![str isEqualToString:@""])) {
                [[SensorsAnalyticsSDK sharedInstance] track:home_otherEntrance_click withProperties:@{@"buttonName":@"其他",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
                TKHPWebController *web = [[TKHPWebController alloc]init];
                web.url = str;
                web.name = @"养老社区";
                [self.navigationController pushViewController:web animated:YES];
            }
        }
        [AppDelegate getAppDelegate].introUrl = dict[@"company"];
        [AppDelegate getAppDelegate].YLUrl = dict[@"community"];
    } failure:^(NSError *error) {
    }];
}
//获取轮播图图片
-(void)getScrollData
{
    //https://isaleuat.taikang.com/isales/carouselfigure/list/waiqingexianxinshouye
    [TKHttpTools POSTWithURL:[TKBaseUrl stringByAppendingString:@"carouselfigure/list/waiqingexianxinshouye"] parameters:@{@"channel":[[TKUserDefaults objectForKey:TKLoginUser] componentsSeparatedByString:@"_"].firstObject} withWay:NO success:^(id responseObject) {
        
        
        if ([responseObject[@"rspDesc"] isEqualToString:@"成功"]) {
            [self.bannerArray removeAllObjects];
            NSArray *array = responseObject[@"info"];
            NSMutableArray *arr = [NSMutableArray array];
            for (int i = 0 ; i<array.count; i++) {
                NSDictionary *dict = array[i];
                TKBannerModel *model = [TKBannerModel initWithDict:dict];
                
                [self.bannerArray addObject:model];
                [arr addObject:model.imgUrl];
                
                
                [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:model.logoUrl] options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                    
                }];
                
            }
            self.circleScrollView.imageUrlStringArray = arr;
//            self.banner.urlImageArr = arr;
        }
        
    } failure:^(NSError *error){
        
    }];
}

/**
 获取今日爆点
 */
// * https://sspuat.taikang.com/agentcenter/honor/getTopPolicyInfo

- (void)getDailyCriticalPointData{
    NSString *url = [TKSeverUrl stringByAppendingString:@"/agentcenter/honor/getTopPolicyInfo"];
    NSString *staff = [TKUserDefaults objectForKey:TKLoginUser];
    
    NSDictionary *param = @{@"agentCode":staff,@"resource":@"1"};
    [TKHttpTools postWithUrl:url paramJSON:param andNeedAlert:NO success:^(id responseObject) {
        if (!([responseObject[@"rspCode"] integerValue] == 0)) {
            return ;
        }
        NSDictionary *info = responseObject[@"info"];
        self.criticalPointPic = info[@"topUrl"];
        NSArray *array = info[@"topInfo"];
        if (array.count == 0) {
            return;
        }
        if (self.expressNewArray.count > 0) {
            [self.expressNewArray removeAllObjects];
        }
        self.expressNewArray = [TKExpressNewModel mj_objectArrayWithKeyValuesArray:array];
        
    } failure:^(NSError *error) {
    }];
}

 //获取泰知乎
 
// * https://sspuat.taikang.com/agentcenter/honor/getTopPolicyInfo

- (void)getTaiZhiHuData{
    //https://tzhqa.taikanglife.com
    NSString *url = @"https://tzhqatest.taikanglife.com/bbs/api/api/user/control/tzhQuestionListByTxx";
    if (isTKProduction) {
        url = @"https://tzhqa.taikanglife.com/bbs/api/api/user/control/tzhQuestionListByTxx";
    }
//    NSString *staff = [TKUserDefaults objectForKey:TKLoginUser];
//
//    NSDictionary *param = @{@"agentCode":staff,@"resource":@"1"};
    [TKHttpTools postWithUrl:(NSString *)url paramDict:nil andNeedAlert:NO success:^(id responseObject) {
        if (!([responseObject[@"rspCode"] integerValue] == 0)) {
            return ;
        }
//        NSDictionary *info = responseObject[@"data"];
        self.taizhihuMoreUrl =responseObject[@"jumpToMoreUrl"];
        [self.taizhihuArray removeAllObjects];
        self.taizhihuArray = [TKTaiZhiHuModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
    }];
}
/**
 获取分公司专区数据
 */
- (void)getBranchCompanyData{
    
    NSString *url = [TKSeverUrl stringByAppendingString:@"/prd/ProductCenter/branch/getBranchUrlByBranchOfficeV2"];
    [TKHttpTools POSTWithURL:url parameters:nil withPost:NO andNeedAlert:NO success:^(id responseObject) {
        if ([responseObject[@"rspDesc"] isEqualToString:@"成功"]) {
            [self.branchCompanyArray removeAllObjects];
            NSArray *arr = responseObject[@"info"][@"branchInfoList"];
            for (NSDictionary *dic in arr) {
                TKBranchCompanyModel *model = [TKBranchCompanyModel mj_objectWithKeyValues:dic];
                model.timestamp = responseObject[@"info"][@"timestamp"];
                [self.branchCompanyArray addObject:model];
            }
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        
    }];
}

/**
 * 获取首页微海报数据
 */
- (void)getHomeWeiHaiBaoData
{
    WeakSelf
    NSString * urlStr = [TKBaseUrl stringByAppendingString:@"poster/getFindPosterList"];
    NSDictionary * param =  @{@"channel":[TKLocalManager sharedManager].channel};
    
    [TKHttpTools getWithUrl:urlStr paramDict:param andNeedAlert:NO success:^(id responseObject) {
        [TKLoadingHUD dismiss];
        NSMutableDictionary * temDict = [NSMutableDictionary dictionaryWithDictionary:responseObject];
//        if (temArray.count > 0) {
//            _haiBaoSectionHeight = 261;
//        }else{
//            _haiBaoSectionHeight = 94;
//        }
        weakSelf.haiBaoResonsed = [NSDictionary dictionaryWithDictionary:temDict];
        [weakSelf.tableView reloadData];
    } failure:^(NSError *error) {
        [TKLoadingHUD dismiss];
    }];
}

/**
 * 请求直播、短视频数据
 */
/**
 * 请求直播、短视频数据
 */
- (void)getLiveAndVideoData
{
    NSString * urlStr = @"https://txxliveuat.taikang.com/isales/shortvideo/liveAndVideoNew";
    if (isTKProduction) {
        urlStr = @"https://txxlive.taikang.com/isales/shortvideo/liveAndVideoNew";
    }
    [TKHttpTools postWithUrl:urlStr paramDict:[NSDictionary dictionary] andNeedAlert:NO success:^(id responseObject) {
        TKLog(@"%@",responseObject);
        
        self.liveVideoDict = [NSMutableDictionary dictionaryWithDictionary:responseObject[@"info"]];
        [self.customerTimer.temTimer invalidate];
        self.customerTimer.temTimer = nil;
        self.customerTimer = nil;
        self.secondCount = 0;
        NSArray * liveDictArray = _liveVideoDict[@"live"];
        __weak typeof(self) weakSelf = self;
        [liveDictArray enumerateObjectsUsingBlock:^(NSDictionary * obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString * statusStr = [obj valueForKey:@"status"];
            if ([statusStr isEqualToString:@"2"]) {
                //表示有直播倒计时，开启定时器
//                self.secondCount = 0;
                //创建定时器
                TKCustomerTimer * customerTimer = [[TKCustomerTimer alloc]init];
                customerTimer.temTimer = [NSTimer timerWithTimeInterval:1.0 target:[TKTimeProxy proxyWithTarget:self] selector:@selector(tem) userInfo:nil repeats:YES];
                [[NSRunLoop mainRunLoop]addTimer:customerTimer.temTimer forMode:NSRunLoopCommonModes];
                weakSelf.customerTimer = customerTimer;
                *stop = YES;
            }
        }];
        
    } failure:^(NSError *error) {
        TKLog(@"%@",error);
    }];
    
}
/**
 * 请求点播数据
 */
- (void)getdianboVideoData
{
    WeakSelf
    NSString * urlStr = @"https://txxliveuat.taikang.com/isales/live/getHomePageVideoList";
    if (isTKProduction) {
        urlStr = @"https://txxlive.taikang.com/isales/live/getHomePageVideoList";
    }
     //2 个险续期
      BOOL isxuqi =  [[TKLocalManager sharedManager].branchType isEqualToString:@"2"];
       NSDictionary *param = @{
           @"identity":@"1",@"isXq":[NSString stringWithFormat:@"%d",isxuqi]};
    [TKHttpTools getWithUrl:urlStr paramDict:param andNeedAlert:NO success:^(id responseObject) {
        TKLog(@"%@",responseObject);
        
        NSDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:responseObject[@"data"]];
        self.dianboArr = [TKGeXianWaiQinDianBoModel mj_objectArrayWithKeyValuesArray:dic[@"liveVideoList"]];
        self.dianboMoreUrl = dic[@"jumpUrl"];
        [weakSelf.tableView reloadData];
    } failure:^(NSError *error) {
        TKLog(@"%@",error);
    }];
    
}

- (void)tem{
    self.secondCount ++;
}
#pragma mark -获取展业证权限
- (void)getZYLimit{
    
    NSString *url = @"https://sspuat.taikang.com/prd/ProductCenter/queryAgentBusinessNo";
    if (isTKProduction) {
        url = @"https://ssp.taikang.com/prd/ProductCenter/queryAgentBusinessNo";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setObject:[TKLocalManager sharedManager].channel forKey:@"sysChannel"];
    [param setObject:[TKLocalManager sharedManager].companyCode forKey:@"agentCompany"];
    [param setObject:[TKLocalManager sharedManager].staffNumber forKey:@"agentNo"];
    [TKHttpTools postWithUrl:url paramJSON:param andNeedAlert:NO success:^(id responseObject) {
        self.hasHKLimit = [responseObject[@"info"][@"businessNo"] boolValue];
        if (self.hasHKLimit) {
            NSString *tips = responseObject[@"info"][@"tips"];
            if (tips!=nil && tips.length>0) {
                TKZYTipsView *zyView = [[NSBundle mainBundle] loadNibNamed:@"TKZYTipsView" owner:nil options:nil].lastObject;
                zyView.frame = CGRectMake(0, 0, TKScreenWidth, TKScreenHeight);
                zyView.tipsLabel.text = tips;
                [TKKeywindow addSubview:zyView];
            }else{
               [self getHuoKeData];
            }
            
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

/**
 获取获客专区数据
 */
- (void)getHuoKeData{
    
    NSMutableDictionary *param = [NSMutableDictionary new];
    param[@"staffNumber"] = [TKLocalManager sharedManager].userID;
    param[@"roles"]= [TKLocalManager sharedManager].userRoles;
    param[@"version"] = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    param[@"os"] = @"ios";
    if ([[TKLocalManager sharedManager].channel isEqualToString:@"3"]){//银保
        param[@"branchType"]= [TKLocalManager sharedManager].branchType;
    }else if([[TKLocalManager sharedManager].channel isEqualToString:@"4"]){//电销
        param[@"f25"]= [TKLocalManager sharedManager].f25;
    }
        
//    NSString *url = [TKHKUrl stringByAppendingString:@"getHkListC"];
    NSString *url = @"http://titantest.mobile.taikang.com/gatewayServer/ProductCenter/getHkListC";
    [TKHttpTools postWithUrl:url paramJSON:param andNeedAlert:NO success:^(id responseObject) {
        if ([responseObject[@"rspDesc"] isEqualToString:@"成功"]) {
            [self.huokeArray removeAllObjects];
            self.huokeArray = [TKHuoKeModel mj_objectArrayWithKeyValuesArray:responseObject[@"info"]];
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        
    }];
}
-(void)loadNew
{
    if (self.isRefreshing) {
        [self.tableView.mj_header endRefreshing];
        return;
    }
    if (!self.bannerArray.count) {
        [self getScrollData];
    }
//    if (!self.secondBannerArray.count) {
//        [self getBannerScrollData];
//    }
    if (!self.huokeArray.count){
        [self getZYLimit];
        [self getBranchCompanyData];
    }
    self.isRefreshing = YES;
    [self getHomeKnowledgeData];
    [self getHomeWeiHaiBaoData];
    [self getLiveAndVideoData];
    [self getdianboVideoData];
    [self getTaiZhiHuData];
    [self getIntelAssistData];
    [self queryUnReadCount];
}

- (void)queryUnReadCount{
    
    NSString *url = [TKBaseUrl stringByAppendingString:@"queryRobot"];
    [TKHttpTools getWithUrl:url paramDict:nil andNeedAlert:NO success:^(id responseObject) {
        NSString *redDotCount = responseObject[@"info"][@"redDotCount"];
        if (IsEmptyValue(redDotCount)) {
            redDotCount = @"0";
        }
        [self setAppBadge:redDotCount];
    } failure:^(NSError *error) {
        
    }];
}
- (void)setAppBadge:(NSString *)badgeNum{
    
    NSInteger unReadCount = [badgeNum integerValue];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:unReadCount];
    [JPUSHService setBadge:unReadCount];
}


/// 获取智能助理数据
- (void)getIntelAssistData{
    [self.intelAssistViewModel getIntelAssistDataWithParams:@{} success:^{
        [UIView performWithoutAnimation:^{
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
        }];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}
/**
* 获取首页发现数据
 */
- (void)getHomeKnowledgeData
{

    NSString * urlStr = [TKDBBQUrl stringByAppendingString:@"oml/getOMHomeList"];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    dict[@"page"] = @"1";
    dict[@"length"] = @"6";
    [TKHttpTools postWithUrl:urlStr paramJSON:dict andNeedAlert:NO success:^(id responseObject) {
        TKLog(@"%@",responseObject);
//        [self.array removeAllObjects];
        NSArray * listArray = responseObject[@"info"][@"list"];
        if (IsEmptyValue(listArray)) {
            listArray = [NSArray array];
        }
        self.array = [TKHomeKnowledgeModel mj_objectArrayWithKeyValuesArray:listArray];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        self.isRefreshing = NO;
        self.moreItemUrl = [NSString stringWithFormat:@"%@",responseObject[@"info"][@"homeUrl"]];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        TKLog(@"%@",error);
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        self.isRefreshing = NO;
    }];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 9;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section == 0){
        //今日爆单
        if (self.expressNewArray.count != 0) {
            return 1;
        }
        return 0;
    }
    if (section==1) {
        return [self.intelAssistViewModel tableView:tableView numberOfRowsInSection:section];
    }
    if (section == 2) {
        //分公司专区和客户经营
        return 1;
    }
    if (section == 3 ) {
        //获客专区
        if (self.huokeArray.count != 0) {
            return 1;
        }
        return 0;
        
    }

    
    
    if (section == 4 ) {
        //taizhihu
        if (self.taizhihuArray.count != 0) {
            return 1;
        }
        return 0;
    }
    
    if (section == 5) {
        //微海报、短视频
            return 1;
    }
    if (section == 6) {
        //2020年10月22日10:48:34 改成头条了
        return 1;
    }
     if (section == 7) {
     return self.array.count ;
     }
    if (section == 8) {
    return 0;
    }
    else{
//        return 4;
        return 1;
    }
    
}
//- (void)tableView:(UITableView *)tableView willDisplayCell:(TKHuoKeZhuanQuTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.section == 3 ) {
//        [cell.myCollectionView setContentOffset:CGPointMake(0, 0)];
//        [cell setCollectionViewDataSourceDelegate:self indexPath:indexPath];
//    }
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self)weakSelf = self;
    if(indexPath.section == 1){
        UITableViewCell *cell = [self.intelAssistViewModel tableView:tableView cellForRowAtIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    if(indexPath.section == 0){
        TKExpressNewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TKExpressNewsCell"];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (nil == cell){
            cell = [[TKExpressNewsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TKExpressNewsCell"];
        }
            [cell.criticalPointImageView  sd_setImageWithURL:[NSURL URLWithString:self.criticalPointPic] placeholderImage:[UIImage imageNamed:@""]];
        if (self.expressNewArray.count > 0) {
            cell.expressNewArray = [NSMutableArray arrayWithArray:self.expressNewArray];
        }
        __weak typeof(cell)weakCell = cell;
        
        cell.rollingViewDidClick = ^(NSInteger index,TKExpressNewModel *model) {
            //点击今日爆点
                TKWebViewController *receiptVC = [[TKWebViewController alloc]initWithUrl:isTKProduction ? @"https://ssp.taikang.com/prd/static/huoke/myHonor/#/explosionPointModule?hasTitle=f&origin=homePage" : @"https://sspuat.taikang.com/prd/jygk/myHonor/#/explosionPointModule?hasTitle=f&origin=homePage"];
                [self.navigationController pushViewController:receiptVC animated:YES];
            [[SensorsAnalyticsSDK sharedInstance] track:home_messages_click withProperties:@{@"type":model.policyTypeName?:@"",@"title":model.text?:@"",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
             return;
        };
        cell.signinBlock = ^(UIButton *sender) {
            TKSuggestViewController *vc = [[TKSuggestViewController alloc]init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        return cell;
    }
    if (indexPath.section == 2) {
        TKCompanyAndEBStoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GeXianWaiQinCompanyAndEBStoreCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.didClickCompany = ^{
            if (self.branchCompanyArray.count == 0) {
                return;
            }
            TKWebViewController *webVC = [[TKWebViewController alloc]init];
                TKBranchCompanyModel *model = self.branchCompanyArray[indexPath.row];
                NSMutableDictionary *param = [NSMutableDictionary dictionary];
                param[@"userid"]    = [TKLocalManager sharedManager].userID;
                param[@"usertype"]  = [TKLocalManager sharedManager].userType;
                param[@"state"]     = @"branch";
                param[@"channel"]   = @"isales-ios";
                param[@"timestamp"] = [NSDate date].timestamp;
                param[@"secret"]  = model.secret;
                param[@"address"] = [TKLocationManager sharedManager].locationModel.address;
                NSString *token     = [TKURLUtil getUrlToken:param];
            
                param[@"token"]     = token;
                param[@"hasTitle"]  = model.hasTitle;
                param[@"r"]         = [NSDate date].timestamp;
                webVC.url = [TKURLUtil appendUrl:model.branchRedirectUrl withParams:param];
                [[SensorsAnalyticsSDK sharedInstance] track:home_otherEntrance_click withProperties:@{@"buttonName":@"分公司专区",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
                [self.navigationController pushViewController:webVC animated:YES];
        };
        cell.didClickEBShop = ^{
            [[SensorsAnalyticsSDK sharedInstance] track:home_otherEntrance_click withProperties:@{@"buttonName":@"E保商城",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
            TKWebViewController *webvc = [[TKWebViewController alloc] init];
            webvc.url = isTKProduction?@"https://lucky.mobile.taikang.com/weiShop/#/home?hasTitle=y":@"https://luckyuat.mobile.taikang.com/weiShop/#/home?hasTitle=y";
            [self.navigationController pushViewController:webvc animated:YES];
        };
        return cell;
    }
    if(indexPath.section == 3){
        TKHuoKeZhuanQuTableViewCell *cell =(TKHuoKeZhuanQuTableViewCell*) [tableView dequeueReusableCellWithIdentifier:@"huokezhuanqu" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.huokeArray = self.huokeArray;
        cell.fromStyle = @"huoke";
        [cell setCollectionContent];
        [cell.myCollectionView reloadData];
        cell.itemDidClick = ^(TKHuoKeModel * _Nonnull model) {

            [[SensorsAnalyticsSDK sharedInstance] track:home_customerManage_click withProperties:@{@"buttonName":model.productName?model.productName:@"",@"type":@"活动",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
                TKWebViewController *webvc = [[TKWebViewController alloc]init];
                webvc.url = model.sharePageUrl;
                if (model.ID.length <= 0) {
                    webvc.url = model.sharePageUrl;
                }else if ([webvc.url containsString:@"?"]) {
                    webvc.url = [NSString stringWithFormat:@"%@&hkId=%@",model.sharePageUrl,model.ID];
                }else{
                    webvc.url = [NSString stringWithFormat:@"%@?hkId=%@",model.sharePageUrl,model.ID];
                }
                if (model.shareUrl.length > 0) {
                    TKShareModel *shareModel = [[TKShareModel alloc]initWithShareUrl:model.shareUrl shareTitle:model.shareTitle shareBitmap:model.shareImgUrl shareIntroduce:model.shareText secret:@""];
                       webvc.shareModel = shareModel;
                }
                if ([model.isToTaiLife isEqualToString:@"1"]) {
                    webvc.taiLifeUrl = model.changeLinkTaiLife;
                    webvc.productName = model.productName;
                }
                if(model.detailTitle.length == 0){
                    webvc.title = model.shareTitle;
                }else{
                    webvc.title = model.detailTitle;
                }
                if ([model.isShareQy isEqualToString:@"1"]) {
                    TKShareWWKModel *shareWWKModel = [[TKShareWWKModel alloc]initWithShareUrl:model.shareLinkQy shareTitle:model.shareTitleQy shareBitmap:model.shareImgUrlQy shareIntroduce:model.shareResumeQy];
                    webvc.shareWWKModel = shareWWKModel;
                }
                if([model.isShareCode isEqualToString:@"1"]){
                    NSString *qrcodeUrl = isTKProduction ? @"https://ssp.taikang.com/prd/static/huoke/QRDetail/index.html#/" : @"https://sspuat.taikang.com/prd/huoke/QRDetail/index.html#/";
                    qrcodeUrl = [qrcodeUrl stringByAppendingString:[NSString stringWithFormat:@"?staffNumber=%@&hkId=%@",[TKLocalManager sharedManager].userID,model.ID]];
                    webvc.qrShowUrl = qrcodeUrl;
                }
                webvc.funcItemDicClick = ^(NSInteger funcId, id funcInfo) {
                if (funcId == 2) {
                   [TKHttpTools postWithUrl:[TKHKUrl stringByAppendingString:@"weChatCodeRecord"] paramJSON:@{@"staffNumber":[TKLocalManager sharedManager].userID,@"productCode":model.productCode} andNeedAlert:NO success:^(id responseObject) {
                       TKLog(@"%@",responseObject);
                   } failure:^(NSError *error) {
                       TKLog(@"%@",error);
                   }];
                }
                };
                [self.navigationController pushViewController:webvc animated:YES];
            };
        cell.taiZhiHuitemDidClick = ^(TKTaiZhiHuModel * model) {
//            TKWebViewController *webvc = [[TKWebViewController alloc]init];
//            webvc.url = model.jumpToUrl;
//            [self.navigationController pushViewController:webvc animated:YES];

        };
//        [cell addCollection];
        return cell;
    }

    if ((!self.array.count)&&([AppDelegate getAppDelegate].status == NotReachable)) {//如果第一次进去出现没有网的情况
        TKErrorTableViewCell *cell = [TKErrorTableViewCell cellWithTabView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.isNotFull = YES;
        cell.refreshBlock = ^{
            [weakSelf.tableView.mj_header beginRefreshing];
        };
        cell.errorType = TKErrorTypeNoInternet;
        return cell;
    }else if ((!self.array.count) && (self.errorHappen==2))//其他得不到数据的情况
    {
        TKErrorTableViewCell *cell = [TKErrorTableViewCell cellWithTabView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.isNotFull = YES;
        cell.refreshBlock = ^{
            [weakSelf.tableView.mj_header beginRefreshing];
        };
        cell.errorType = TKErrorTypeUnknownError;
        return cell;
    }else if ((!self.array.count)&& (self.errorHappen==1))
    {
        TKErrorTableViewCell *cell = [TKErrorTableViewCell cellWithTabView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.isNotFull = YES;
        cell.refreshBlock = ^{
            [weakSelf.tableView.mj_header beginRefreshing];
        };
        cell.errorType = TKErrorTypeNoNeiRong;
        return cell;
    }else if(indexPath.section == 4)
    {
        TKHuoKeZhuanQuTableViewCell *cell =(TKHuoKeZhuanQuTableViewCell*) [tableView dequeueReusableCellWithIdentifier:@"taizhihu" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.taizhihuArray = self.taizhihuArray;
        cell.fromStyle = @"taizhihu";
        cell.taiZhiHuitemDidClick = ^(TKTaiZhiHuModel * model) {
            TKWebViewController *webvc = [[TKWebViewController alloc]init];
            webvc.url = model.jumpToUrl;
            [self.navigationController pushViewController:webvc animated:YES];
            [[SensorsAnalyticsSDK sharedInstance] track:home_content_click withProperties:@{@"contentType":@"泰知乎",@"num":[NSString stringWithFormat:@"%ld",(long)indexPath.row+1],@"contentId":model.ID?model.ID:@"",@"title":model.title?model.title:@"",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
        };
        [cell setCollectionContent];
        [cell.myCollectionView reloadData];
//        //2020年10月21日15:40:37 改为分公司专区
//        NSString *ID = @"TKBranchCompanyCell";
//        TKBranchCompanyCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
//        if (cell == nil) {
//            cell = [[[NSBundle mainBundle]loadNibNamed:@"TKBranchCompanyCell" owner:self options:nil]lastObject];
//        }
//        if (self.branchCompanyArray.count > 0) {
//            cell.model = self.branchCompanyArray[indexPath.row];
//        }
        return cell;
    }else if (indexPath.section == 5){
        //已改成微海报与短视频
                TKGeXianWaiQinHaiBaoAndShorVideoCell * cell = [TKGeXianWaiQinHaiBaoAndShorVideoCell haibaoAndVideoCellWithTable:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.isLiveState = self.videoState;
                cell.currentStateBlock = ^(GeXianWaiQinSelectBtnType btnType) {
                    if (btnType == GeXianWaiQinselectBtnTypeVideo) {
                        weakSelf.videoState = YES;
                    }else{
                        weakSelf.videoState = NO;
                    }
        //            weakSelf.videoState = isHaibaoState;
                };
                cell.responseObject = self.haiBaoResonsed;
                cell.liveVideoDict = self.liveVideoDict;
                return cell;

    }else if(indexPath.section == 6){
        //2020年10月21日14:29:27 要改为新直播
        if (self.isLive) {
            TKGeXianWaiQinHomeLiveTableViewCell * cell = [TKGeXianWaiQinHomeLiveTableViewCell homeLiveCellWithTable:tableView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.hasPassedSeconds = self.secondCount;
//            cell.isLive = self.isLive;
//            if (self.isLive) {
                cell.liveDict = self.liveVideoDict;
//            }else{
//                cell.liveDict = self.dianboDict;
//            }
            return cell;
        }else{
            TKHuoKeZhuanQuTableViewCell *cell =(TKHuoKeZhuanQuTableViewCell*) [tableView dequeueReusableCellWithIdentifier:@"dianbo" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.zhibodianboArray = self.dianboArr;
            cell.fromStyle = @"zhibodianbo";
            cell.zhibodianbotemDidClick = ^(TKGeXianWaiQinDianBoModel * _Nonnull model) {
                TKWebViewController *webvc = [[TKWebViewController alloc]init];
                webvc.url = model.videoUrl;
                [self.navigationController pushViewController:webvc animated:YES];

                [[SensorsAnalyticsSDK sharedInstance] track:home_content_click withProperties:@{@"contentType":@"点播",@"num":[NSString stringWithFormat:@"%ld",(long)indexPath.row+1],@"contentId":model.liveId?model.liveId:@"",@"title":model.title?model.title:@"",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
            };
            
            [cell setCollectionContent];
            [cell.myCollectionView reloadData];
            return cell;
        }
        
    }else if (indexPath.section == 7){
        if (indexPath.row == self.array.count) {
            TKGeXianWaiQinTouTiaoLastCell *cell = (TKGeXianWaiQinTouTiaoLastCell *)[tableView dequeueReusableCellWithIdentifier:@"toutiaolast" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;

        }else{
        TKHomeNewTouTiaoTableCell * cell = [TKHomeNewTouTiaoTableCell homeNewTouTiaoCellWithTable:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (self.array.count > 0) {
         cell.model = self.array[indexPath.row];
        }
            return cell;

        }
        
    }
    return [[UITableViewCell alloc]init];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1){
        return [self.intelAssistViewModel tableView:tableView heightForRowAtIndexPath:indexPath];
    }
    if(indexPath.section == 0){
        if (self.expressNewArray.count == 0) {
            return CGFLOAT_MIN;
        }
        return kFitRatio_750(79);
    }
    if(indexPath.section == 2){
        return kFitRatio_750(130);
    }
    if (indexPath.section == 3) {
        if (self.huokeArray.count == 0) {
            return CGFLOAT_MIN;
        }
          return kFitRatio_750(100);
    }
    if (indexPath.section == 4) {
        if(self.taizhihuArray.count == 0){
            return CGFLOAT_MIN;
        }
        return 211;
    }
    
    
    if (indexPath.section == 5) {
        //2020年10月22日09:31:03改为短视频、微海报
        return kFitRatio_750(235);
    }
    
    if (indexPath.section == 6) {
       //2020年10月21日14:33:40这里要改为新直播
        NSArray * temArray = [NSArray array];
        if (self.isLive) {
            if (!IsEmptyValue(_liveVideoDict[@"live"])) {
                temArray = _liveVideoDict[@"live"];
            }
            if (IsEmptyValue(_liveVideoDict)|| temArray.count == 0) {
                return CGFLOAT_MIN;
            }
        }else{
            if (self.dianboArr.count == 0) {
                return CGFLOAT_MIN;
            }
        }
                
        return kFitRatio_750(135)   ;
    }
    if (indexPath.section == 7) {
        if (indexPath.row == self.array.count) {
            return kFitRatio_750(15)+10;
        }
         return kFitRatio_750(100)+10;
    }
    if (((self.array.count == 0)&&(([AppDelegate getAppDelegate].status == NotReachable)||(self.errorHappen)))) {
        return kFitRatio_750(181);
    }
    
    return cellH;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section

{
    return .1;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
     return [[UIView alloc]init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0 || section == 2){
        return CGFLOAT_MIN;
    }
    if(section == 1 && !self.intelAssistViewModel.intelAssistModel){
        return CGFLOAT_MIN;
    }
    if (section == 3 &&self.huokeArray.count ==0) {
        return CGFLOAT_MIN;
    }
    if (section == 4&&self.taizhihuArray.count == 0) {
        return CGFLOAT_MIN;
    }
    if (section == 6) {
        NSArray * temArray = [NSArray array];
            if (!IsEmptyValue(_liveVideoDict[@"live"])) {
                temArray = _liveVideoDict[@"live"];
            }

            if ((IsEmptyValue(_liveVideoDict)|| temArray.count == 0) && self.dianboArr.count== 0) {
                return CGFLOAT_MIN;
            }
               
    }
    if (section == 7 && self.array.count == 0) {
        return CGFLOAT_MIN;
    }
        return kFitRatio_750(45);
}
-(void)hearderIconDidClickInSection:(NSInteger)section{
    if (section == 3 ) {
        [[SensorsAnalyticsSDK sharedInstance] track:home_customerManage_click withProperties:@{@"buttonName":@"智能面访",@"type":@"功能",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
        [self showFaceData];

    }
    if (section == 5 ) {
        TKWebViewController * webVc = [[TKWebViewController alloc]init];
        NSString * url = @"https://sspuat.taikang.com/prd/MORE/cflist/#/?hasTitle=y&functionId=OnceADay";
        if (isTKProduction) {
            url = @"https://ssp.taikang.com/prd/static/MORE/cfList/#/?hasTitle=y&functionId=OnceADay";
        }
        webVc.url = url;
        [self.navigationController pushViewController:webVc animated:YES];
        [[SensorsAnalyticsSDK sharedInstance] track:home_content_click withProperties:@{@"contentType":@"微海报",@"title":@"每日一圈",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
    }
    if (section == 7 ) {
        [self jumpToTwtx];
        [[SensorsAnalyticsSDK sharedInstance] track:home_content_click withProperties:@{@"contentType":@"泰康头条",@"title":@"泰闻天下",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
    }
    if (section == 8 ) {
        //pages/index/index
        //原始ID：gh_26afbcb84f43
//        NSString *envType = isTKProduction ?@"release":@"test";
        [[SensorsAnalyticsSDK sharedInstance] track:home_aboutTK_click withProperties:@{@"buttonName":@"泰康人寿报",@"businessLine": @"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
        NSString *envType = @"release";
        NSDictionary *param = @{@"miniId":@"gh_26afbcb84f43",@"path":@"pages/index/index",@"envType":envType};
        [self openMiniProjectByNative:param ];
        
        
    }
}
/// 拉起小程序
- (void)openMiniProjectByNative:(NSDictionary *)params{
    if(![TKShareManager isWXAppInstalled]){
        [AutoAlertView ShowMessage:@"未安装微信"];
        return;
    }
    if (!params || ![params isKindOfClass:[NSDictionary class]]) {
        return;
    }
    NSString *miniId = params[@"miniId"];
    NSString *path = params[@"path"];
    NSString *envType = params[@"envType"];
    // envType (test  测试版  preview  体验版  release 正式版  )
    NSInteger miniProgramType = 0;
    if ([envType isEqualToString:@"test"]) {
        miniProgramType = 1;
    }else if ([envType isEqualToString:@"preview"]) {
        miniProgramType = 2;
    }else{
        miniProgramType = 0;
    }
    [TKShareManager launchMiniProgram:miniId path:path envType:miniProgramType completion:^(int errorCode, NSString *errorMsg) {
        if (errorCode == 0) {
//            [AutoAlertView ShowMessage:@"未安装微信"];
        }else{
            [AutoAlertView ShowMessage:@"跳转失败"];
        }
    }];

}
- (void)hearderMoreBtnClickInSection:(NSInteger)section{
    if (section == 1) {
        NSString *url = [self.intelAssistViewModel getJumpUrlWithMoreClickInfo];
        NSString *type = self.intelAssistViewModel.intelAssistModel.titleInfo[self.intelAssistViewModel.intelAssistModel.selectIndex].title;
        [[SensorsAnalyticsSDK sharedInstance] track:home_intelligentAssistant_click withProperties:@{@"type":type ? type: @"",@"title": @"更多", @"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
        if (url.length == 0) {
            return;
        }
        TKWebViewController *webVC = [[TKWebViewController alloc]init];
        webVC.url = url;
        [self.navigationController pushViewController:webVC animated:YES];
        return;
    }
    if (section ==3) {
        TKWebViewController *webVC = [[TKWebViewController alloc]init];
//                       webVC.url = isTKProduction ? @"https://ssp.taikang.com/prd/static/huoke/HKListRework/index.html?hasTitle=y" : @"https://sspuat.taikang.com/prd/huoke/HKListRework/index.html?hasTitle=y";
        webVC.url = isTKProduction ? @"https://ssp.taikang.com/prd/static/huoke/HKListRework/index.html?hasTitle=y" : @"https://titantest.mobile.taikang.com/productcenter/#/home?hasTitle=y";

                       [self.navigationController pushViewController:webVC animated:YES];
        [[SensorsAnalyticsSDK sharedInstance] track:home_customerManage_click withProperties:@{@"buttonName":@"更多",@"type":@"功能",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
        return;
    }
    if (section ==5) {
        if (!self.videoState ) {
//            TKWHBViewController *momentVC = [[TKWHBViewController alloc] init];
//
//            NSMutableDictionary * param = [NSMutableDictionary dictionary];
//            param[@"type"] = @"1";
            [[SensorsAnalyticsSDK sharedInstance] track:home_content_click withProperties:@{@"contentType":@"微海报",@"title":@"更多",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
			TKWebViewController * webVc = [[TKWebViewController alloc]init];
			NSString *urlStr = @"";
			if (isTKProduction) {
				urlStr = @"https://ssp.taikang.com/prd/customerCenter/microPoster/#/poster?hasTitle=f";
			}else{
				urlStr = @"https://sspuat.taikang.com/prd/huoke/microPoster/#/poster?hasTitle=f";
			}
			webVc.url = urlStr;
            [self.navigationController pushViewController:webVc animated:YES];
        }else{
            TKWebViewController * webVc = [[TKWebViewController alloc]init];
            webVc.url = _liveVideoDict[@"shortListUrl"];
            NSMutableDictionary * param = [NSMutableDictionary dictionary];
            param[@"type"] = @"1";
            [[SensorsAnalyticsSDK sharedInstance] track:home_content_click withProperties:@{@"contentType":@"短视频",@"title":@"更多",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
            [self.navigationController pushViewController:webVc animated:YES];
        }
        return;
    }
    if (section ==4) {
        TKWebViewController * webVc = [[TKWebViewController alloc]init];
        webVc.url = self.taizhihuMoreUrl;
        [[SensorsAnalyticsSDK sharedInstance] track:home_content_click withProperties:@{@"contentType":@"泰知乎",@"title":@"更多",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
        [self.navigationController pushViewController:webVc animated:YES];
       return;
    }
    if (section ==6) {
        if (self.isLive) {
            [[SensorsAnalyticsSDK sharedInstance] track:home_content_click withProperties:@{@"contentType":@"精彩直播",@"title":@"更多",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
        }else{
            [[SensorsAnalyticsSDK sharedInstance] track:home_content_click withProperties:@{@"contentType":@"热门点播",@"title":@"更多",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
        }
        
        //这里添加跳转直播
        TKWebViewController * webVc = [[TKWebViewController alloc]init];
        NSString * urlStr = @"https://txxliveuat.taikang.com/static/directSeeding/index.html#/?hasTitle=y";
        if (isTKProduction) {
            urlStr = @"https://txxlive.taikang.com/static/directSeeding/index.html#/?hasTitle=y";
        }
        if (!self.isLive) {
            urlStr = self.dianboMoreUrl;
//            if (isTKProduction) {
//                urlStr = @"https://txxlive.taikang.com/static/directSeeding/index.html#/?hasTitle=y";
//            }
        }
        webVc.url = urlStr;
        [self.navigationController pushViewController:webVc animated:YES];
        return;
    }
    if (section ==7) {
        [self jumpToKnowledgeItemMore];
        [[SensorsAnalyticsSDK sharedInstance] track:home_content_click withProperties:@{@"contentType":@"泰康头条",@"title":@"更多",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
        return;
    }
    if (section ==8) {
        return;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    __weak typeof (self)weakSelf = self;
    if(section == 0 || section == 2){
        UIView *headerView = [[UIView alloc]init];
        headerView.backgroundColor = TKGrayGroundColor;
        return headerView;
    }
    if(section == 1 && !self.intelAssistViewModel.intelAssistModel){
        return [[UIView alloc]init];
    }
//    if (section >= 2&& section<=4) {
    TKGeXianWaiQinHomepageHeader *header = [[[NSBundle mainBundle] loadNibNamed:@"TKGeXianWaiQinHomepageHeader" owner:self options:nil] firstObject];
    header.titleLabel.text = self.headerArray[section];
    header.iconDidClick = ^{
        [self hearderIconDidClickInSection:section];
    };
    header.moreBtnDidClick = ^{
        [self hearderMoreBtnClickInSection:section];
    };
    if (section == 6) {
        [header liveheader];
        NSArray *temArr = self.liveVideoDict[@"live"];
        if (IsEmptyValue(_liveVideoDict[@"live"]) || temArr == 0) {
            header.titleLabel.hidden = YES;
        }
        if (self.dianboArr.count == 0)  {
            header.secondTitleLabel.hidden = YES;
        }
        if (self.isLive) {
            header.secondTitleLabel.font = [UIFont systemFontOfSize:kFitRatio_750(16)];
            header.titleLabel.font = [UIFont systemFontOfSize:kFitRatio_750(18) weight:UIFontWeightMedium];
            header.secondTitleLabel.textColor = [UIColor colorWithHexString:@"#999999"];
            header.titleLabel.textColor = [UIColor colorWithHexString:@"#333333"];
            header.tagViewCenterX.constant = 0;
            
        }else{
            header.secondTitleLabel.font = [UIFont systemFontOfSize:kFitRatio_750(18) weight:UIFontWeightMedium] ;
            header.titleLabel.font = [UIFont systemFontOfSize:kFitRatio_750(16) ];
            header.titleLabel.textColor = [UIColor colorWithHexString:@"#999999"];
            header.secondTitleLabel.textColor = [UIColor colorWithHexString:@"#333333"];

            header.tagViewCenterX.constant = header.secondTitleLabel.centerX- header.titleLabel.centerX+15;
        }
    }
    header.liveClick = ^(BOOL isLive) {
        self.isLive = isLive;
        [UIView performWithoutAnimation:^{
            [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:6] withRowAnimation:UITableViewRowAnimationNone];
        }];
    };
    
    if (section == 3 ) {
        header.imagename = @"znmfcfj";
        [header showGifImageView];
    }
    if (section == 5 ) {
        header.imagename = @"mryq";
         [header showGifImageView];
    }
    if (section == 7 ) {
        header.imagename = @"twtx";
         [header showGifImageView];
    }
    if(section == 8 ){
        header.imagename = @"tkrsb";
         [header showGifImageView];
     header.moreView.hidden = YES;
        header.moreIMG.hidden = YES;
    }
    if (section == 3 || section == 5|| section == 7 || section == 8) {
        header.mrzbImageView.hidden = NO;
    }else{
        header.mrzbImageView.hidden = YES;
    }
    if (section == 4) {
        header.backView.backgroundColor = [UIColor clearColor];
    }
        return header;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.contentOffset.y <TKScreenHeight) {
            [self.tableView sendSubviewToBack:self.myview ];

    }

}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)indexPath{
    if (tableView.contentOffset.y <TKScreenHeight) {
            [self.tableView sendSubviewToBack:self.myview ];

    }
}


- (void)jumpToTwtx
{
    NSString * urlStr = @"https://luckyuat.mobile.taikang.com/weiShop/#/preDayNewsBlank?hasTitle=y";
    if (isTKProduction) {
        urlStr = @"https://lucky.mobile.taikang.com/weiShop/#/preDayNewsBlank?hasTitle=y";
    }
    TKWebViewController *webVC = [[TKWebViewController alloc]initWithUrl:urlStr];
    [self.navigationController pushViewController:webVC animated:YES];
}

/**
 * 泰康头条点击更多按钮
 */
- (void)jumpToKnowledgeItemMore
{
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    param[@"type"] = @"2";
    TKWebViewController * webVc = [[TKWebViewController alloc]initWithUrl:self.moreItemUrl];
    [self.navigationController pushViewController:webVc animated:YES];
}

- (void) showFaceData{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:[TKLocalManager sharedManager].userIDWithUCM forKey:@"agntNum"];
    WSELF_DEFINE;
    [TKHttpTools getWithUrl:[TKSeverUrl stringByAppendingString:@"/customer/qrCode/getQRCode"] paramDict:param andNeedAlert:YES success:^(id responseObject) {
        if ([responseObject[@"rspCode"] isEqualToString:@"0"]) {
            NSString *str = responseObject[@"info"][@"qrCode"];
           NSString * url = @"";
            if (isTKProduction) {
                if (IsStrEmpty(str)) {//二维码
                    url = [NSString stringWithFormat:@"https://ssp.taikang.com/prd/static/huoke/intellectVisit/index.html#/upload?hasTitle=y"];
                }else{//面访
                    url = [NSString stringWithFormat:@"https://ssp.taikang.com/prd/static/huoke/intellectVisit/index.html#/interview?hasTitle=y"];
                }
            }else{
                if (IsStrEmpty(str)) {
                    url = [NSString stringWithFormat:@"https://sspuat.taikang.com/prd/huoke/intellectVisit/index.html#/upload?hasTitle=y"];
                }else{
                    url = [NSString stringWithFormat:@"https://sspuat.taikang.com/prd/huoke/intellectVisit/index.html#/interview?hasTitle=y"];
                }
            }
            TKWebViewController *vc = [[TKWebViewController alloc]init];
            vc.url = url;
            [self.navigationController pushViewController:vc
                                                     animated:YES];
        }
    } failure:^(NSError *error) {
        
    }];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0 || indexPath.section == 2){
        return;
    }
    if (indexPath.section == 3) {
        return;
    }
    /// 智能助理
    if (indexPath.section == 1) {
        NSString *jumpUrl = [self.intelAssistViewModel getJumpUrlWithSelectAtIndexPath:indexPath];
        if (jumpUrl) {
            TKWebViewController *webVC = [[TKWebViewController alloc]init];
            webVC.url = jumpUrl;
            [self.navigationController pushViewController:webVC animated:YES];
        }
        [self.intelAssistViewModel tableView:tableView didSelectRowAtIndexPath:indexPath];
        return;
    }
    if (indexPath.section == 4) {
        return;
    }
    if (((self.array.count == 0)&&(([AppDelegate getAppDelegate].status == NotReachable)||(self.errorHappen)))) {
        return;
    }
    if (indexPath.section == 7) {
        if (indexPath.row != self.array.count) {
            [self jumpToKnwoledgeWeb:indexPath];
        }
    }
}
- (void)jumpToKnwoledgeWeb:(NSIndexPath *)indexPath{
    TKHomeKnowledgeModel * model = self.array[indexPath.row];

    [[SensorsAnalyticsSDK sharedInstance] track:home_content_click withProperties:@{@"contentType":@"泰康头条",@"num":[NSString stringWithFormat:@"%ld",indexPath.row+1],@"contentId":model.ID?model.ID:@"",@"title":model.title?model.title:@"",@"businessLine":@"外勤新版"} withTrackType:SensorsAnalyticsTrackTypeCode];
    if ([model.showMode isEqualToString:@"3"]) {
        //判断消息类型,贺卡类型
        TKHPWebController *web = [[TKHPWebController alloc]init];
        web.sharePageUrl = model.turnUrl;
        web.name = model.title;
        web.logoUrl = model.iconImgUrl;
        web.intro = model.transDesc;
        web.targetType = @"3";
        //    web.type = self.klModuleModel.moduleId;
        web.ID = model.ID;
        web.pageType = YES;
        web.qyxFlag = model.qyxFlag;
        web.mssFlag = model.mssFlag;
        if ([model.ifTrans isEqualToString:@"1"]) {
            web.needNotShare = YES;
        }
        if ([model.qyxFlag isEqualToString:@"1"]) {
            web.sharePageUrl = model.turnUrl;
        }
        web.url = model.turnUrl;
        [self.navigationController pushViewController:web animated:YES];
        return;
    }
    //跳转新web
    TKWebViewController * newWebVc = [[TKWebViewController alloc]init];
    NSString *operator = [TKUserDefaults objectForKey:TKLoginUser];
    NSString * newStr = [NSString stringWithFormat:@"%@?froms=oml&id=%@&Operator=%@&roles=%@&token=%@",model.url,model.ID,operator,[[[TKLocalManager sharedManager].userRoles mj_JSONString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[TKUserDefaults objectForKey:TKTokenKey]];
    if ([model.showMode isEqualToString:@"3"]) {
        newStr = model.turnUrl;
    }
    newWebVc.url = newStr;
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    param[@"infoId"] = [NSString stringWithFormat:@"%@",model.ID];
    param[@"type"] = [NSString stringWithFormat:@"%@",model.indexMod];
    [self.navigationController pushViewController:newWebVc animated:YES];
    
}
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    // 删除系统自带的tabBarButton
    for (UIView *tabBar in self.tabBarController.tabBar.subviews) {
        if ([tabBar isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            [tabBar removeFromSuperview];
        }
    }
}
/**
 * 关闭ios右滑返回
 */
-(void)cancelSideBack{
    
    self.isCanUseSideBack = NO;
    
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate=self;
    }
}
/*
 开启ios右滑返回
 */
- (void)startSideBack {
    self.isCanUseSideBack=YES;
    
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer*)gestureRecognizer {
    return self.isCanUseSideBack;
}
//-(void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    if ([scrollView isEqual:self.tableView]) {
//        if (scrollView.contentOffset.y<-5) {
////            self.bar.hidden = YES;
//            self.bar.type = 0;
//        }else
//        {
//            self.bar.hidden = NO;
//            CGFloat hei = HEIGHT_PT(326);
//            if ((scrollView.contentOffset.y>(hei/20))) {
//                if ((scrollView.contentOffset.y<hei)) {
//                    self.bar.alpha = scrollView.contentOffset.y/(hei*19/20);
//                    if (self.bar.type == 2) {
//                        return;
//                    }
//                    [self.bar.placeHolder setImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
//                    self.bar.statusBar.height = TKStautsBarH;
//                    self.bar.statusBar.image = nil;
//                    self.bar.statusBar.backgroundColor = TKMainColor;
//                    self.bar.backgroundColor = TKMainColor;
//                    [self.bar.placeHolder setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//                    self.bar.centerTextView.backgroundColor = [UIColor colorWithHexString:@"#ff7043"];
//                    self.bar.type = 2;
//                    self.bar.alpha = scrollView.contentOffset.y/(hei*19/20);
//                }else
//                {
//                    if (self.bar.type == 3) {
//                        return;
//                    }
//                    [self.bar.placeHolder setImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
//                    self.bar.statusBar.height = TKStautsBarH;
//                    self.bar.statusBar.image = nil;
//                    self.bar.statusBar.backgroundColor = TKMainColor;
//                    self.bar.backgroundColor = TKMainColor;
//                    [self.bar.placeHolder setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//                    self.bar.centerTextView.backgroundColor = [UIColor colorWithHexString:@"#ff7043"];
//                    self.bar.type = 3;
//                    self.bar.alpha = 1;
//                }
//            }else
//            {
//                if (self.bar.type == 1) {
//                    return;
//                }
//                [self.bar.placeHolder setImage:[UIImage imageNamed:@"shouye-search"] forState:UIControlStateNormal];
//                self.bar.statusBar.height = TKHeaderH;
//                self.bar.statusBar.backgroundColor = [UIColor clearColor];
//                self.bar.statusBar.image = [UIImage resizableImageWithName:@"shouye-mengceng"];
//                self.bar.backgroundColor = [UIColor clearColor];
//
//                [self.bar.placeHolder setTitleColor:[UIColor colorWithHexString:@"#999999"] forState:UIControlStateNormal];
//                self.bar.centerTextView.backgroundColor = TKColor(255, 255, 255, 0.9);
//                self.bar.alpha = 1;
//                self.bar.type = 1;
//            }
//        }
//    }
//}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    NSInteger currentPage = targetContentOffset->x / TKScreenWidth;

    if(scrollView==self.toolBar){
        self.myPageControl.currentPage = currentPage;
    }
}
//新兵营
- (void)getxinbingyin{
    @weakify(self);
    [TKLoadingHUD showWithTitle:@"加载中..."];
    NSDictionary *dic = @{@"type":@"1"};
    [TKHttpTools getWithUrl:[NSString stringWithFormat:@"%@%@",KBluetoothBaseURL,xinbingying] paramDict:dic andNeedAlert:YES success:^(id responseObject) {
        [TKLoadingHUD dismiss];
        if ([responseObject[@"rspCode"] isEqualToString:@"0"]) {
            NSDictionary *info = responseObject[@"info"];
            if (info && info[@"auth"] && [info[@"auth"] boolValue]) {
                NSString *url = info[@"url"];
                if (url) {
                    TKWebViewController *vc = [[TKWebViewController alloc]init];
                    vc.url = url;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                
            }else{
                [AutoAlertView ShowMessage:@"无考试权限"];
            }
        }
    } failure:^(NSError *error) {
        [TKLoadingHUD dismiss];
    }];
}
- (void)showNewHomeGuide
{
    UIButton * dimView = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, TKScreenWidth, TKScreenHeight)];
    dimView.backgroundColor = [UIColor colorWithRed:100/255.0 green:100/255.0 blue:100/255.0 alpha:0.5];
    [[UIApplication sharedApplication].keyWindow addSubview:dimView];
    
    //添加imageView
    NSString * imageStr = @"ios引导-个险";
    UIImageView * imgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:imageStr]];
    imgView.frame = dimView.bounds;
    [dimView addSubview:imgView];
    [dimView addTarget:self action:@selector(removeGuideImg:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)removeGuideImg:(UIButton *)btn
{
    [btn removeFromSuperview];
}



- (void)getJsPushTags
{
    NSString * urlStr = [TKBaseUrl stringByAppendingString:@"msg/tagList"];
    [TKHttpTools getWithUrl:urlStr paramDict:nil andNeedAlert:NO success:^(id responseObject) {
        
        NSArray * listArray = responseObject[@"info"][@"tagList"];
        if (listArray.count > 0) {
            [AppDelegate appDelegate].JPushTags = [NSArray arrayWithArray:listArray];
        }else{
            [AppDelegate appDelegate].JPushTags = @[];
        }
        [self setPushTas];
    } failure:^(NSError *error) {
        
    }];
}

- (void)setPushTas
{
    if (([AppDelegate getAppDelegate].JPushLoginSuccess)) {
        NSSet *set = [NSSet setWithArray:[AppDelegate getAppDelegate].JPushTags];
        [JPUSHService setTags:set completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
            TKLog(@"首页的设置tag来了回调----iResCode====%ld",(long)iResCode);
        } seq:5];
    }
}

@end
